Question
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Method
Construct a tree based on the middle-order traversal and pre-order traversal of the tree and use recursive thinking.
TreeNode getTree (int [] preorder, int preStart, int preEnd, int [] inorder, int inStart, int inEnd) {if (preStart> = preEnd) {return null ;} int cur = preorder [preStart]; TreeNode root = new TreeNode (cur); int I = 0; int j = inStart; while (inorder [j]! = Cur) {j ++; I ++;} root. left = getTree (preorder, preStart + 1, preStart + I + 1, inorder, inStart, inStart + I); root. right = getTree (preorder, preStart + I + 1, preEnd, inorder, inStart + I + 1, inEnd); return root;} public TreeNode buildTree (int [] preorder, int [] inorder) {if (preorder = null) {return null;} int len = preorder. length; return getTree (preorder, 0, len, inorder, 0, len );}