Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
找出前序遍历中根节点在中序遍历范围中的位置,依次得到
关键在于右子树节点在前序遍历中的位置的得到上要注意
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return helper(0, 0, inorder.length-1, preorder, inorder);
}
private TreeNode helper(int preindex, int instart, int inend, int[] preorder, int[] inorder){
if(preindex>=preorder.length || instart>inend) return null;
int index = 0;
for(int i=instart; i<=inend; i++){
if(inorder[i]==preorder[preindex]) index = i;
}
TreeNode root = new TreeNode(preorder[preindex]);
root.left = helper(preindex+1, instart, index-1, preorder, inorder);
root.right = helper(preindex-instart+index+1, index+1, inend, preorder, inorder);
return root;
}
}