Niu Ke (4) Rebuild the binary tree

//Title description 
// Input the result of preorder traversal and inorder traversal of a binary tree, please reconstruct the binary tree.
// Assume that the results of the input preorder traversal and inorder traversal do not contain duplicate numbers.
// For example, enter the preorder traversal sequence {1,2,4,7,3,5,6,8} and the inorder traversal sequence {4,7,2,1,5,3,8,6},
// Then rebuild the binary tree and return.
public class test_4 {

public static class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode(int x) {
val = x;
}
}

public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
TreeNode tree = reConstructBinaryTree (pre, 0, pre.length - 1, in, 0, in.length - 1);
return tree;
}

public static TreeNode reConstructBinaryTree(int[] pre, int preStartIndex, int preEndIndex, int[] in, int inStartIndex, int inEndIndex) {
if (preStartIndex > preEndIndex || inStartIndex > inEndIndex) {
return null;
}
TreeNode tree = new TreeNode(pre[preStartIndex]);

for (int i = inStartIndex; i <= inEndIndex; i++) {
if (pre[preStartIndex] == in[i]) {
tree.left = reConstructBinaryTree(pre, preStartIndex + 1, preStartIndex + i - inStartIndex, in, inStartIndex, i - 1);
tree.right = reConstructBinaryTree(pre, preStartIndex + i - inStartIndex + 1, preEndIndex, in, i + 1, inEndIndex);
}
}
return tree;
}

public static void main(String[] args) {
int preOrder[] = {1, 2, 4, 7, 3, 5, 6, 8};
int inOrder[] = {4, 7, 2, 1, 5, 3, 8, 6};
reConstructBinaryTree(preOrder, inOrder);

}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325220377&siteId=291194637