public class Solution_0064 {
public static TreeNode recurTree(int[] preorder, int preLeft, int preRight, int[] inorder, int inLeft, int inRight) {
TreeNode root = new TreeNode(preorder[preLeft]);
int rootIndex = 0;
for (int i = inLeft; i < inRight + 1; i++) {
if(inorder[i] == root.val) {
rootIndex = i;
break;
}
}
int preIndex = rootIndex - 1 - inLeft + 1;
preIndex = preLeft + 1 + preIndex - 1;
if(rootIndex == inLeft) root.left = null;
else root.left = recurTree(preorder, preLeft + 1, preIndex, inorder, inLeft, rootIndex - 1);
if(rootIndex == inRight) root.right = null;
else root.right = recurTree(preorder, preIndex + 1, preRight, inorder, rootIndex + 1, inRight);
return root;
}
public static TreeNode buildTree(int[] preorder, int[] inorder) {
return recurTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}
public static void main(String[] args) {
System.out.println();
int[] inorder = {9, 3, 15, 20, 7};
int[] pretorder = {3, 9, 20, 15, 7};
TreeNode root = buildTree(pretorder, inorder);
TreeNode root = buildTree(pretorder, inorder);
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(queue.size() > 0) {
int length = queue.size();
while(length-- > 0) {
root = queue.poll();
System.out.print(root.val + "\t");
if(root.left != null) queue.offer(root.left);
if(root.right != null) queue.offer(root.right);
}
}
}
}