public class PreInfixOrderMakeBinaryTree {
public static void main(String[] args) {
int[] preorder = new int[] {1,2};
int[] inorder = new int[] {2,1};
PreInfixOrderMakeBinaryTree t = new PreInfixOrderMakeBinaryTree();
TreeNode root = t.buildTree(preorder,inorder);
System.out.println(root);
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || preorder.length == 0 || inorder == null || inorder.length == 0) {
return null;
}
TreeNode root = buildTreeByRecursion(preorder,0,preorder.length - 1, inorder,0,inorder.length - 1);
return root;
}
public TreeNode buildTreeByRecursion(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
TreeNode root = new TreeNode(preorder[preStart]);
if (preStart == preEnd && inStart == inEnd) {
return root;
}
int rootIndex = 0;
for (int i = inStart; i <= inEnd; i ++) {
if (inorder[i] == preorder[preStart]) {
rootIndex = i;//找到根节点在中序遍历序列中的下标
break;
}
}
int leftLength = rootIndex - inStart;//根节点的左孩子的个数
int rightLength = inEnd - rootIndex;//根节点右孩子的个数
//根节点的左孩子的个数大于0
if (leftLength > 0) {
root.left = buildTreeByRecursion(preorder,preStart + 1, preStart + leftLength,
inorder,inStart,rootIndex - 1);
}
if (rightLength > 0) {
root.right = buildTreeByRecursion(preorder,preStart + 1 + leftLength,preEnd,
inorder,rootIndex + 1, inEnd);
}
return root;
}
}
根据前序遍历和中序遍历构件二叉树的思路及JAVA实现
最新推荐文章于 2024-08-26 16:40:46 发布