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 preStart, int inStart, int inEnd, int[] preorder, int[] inorder){
if(preStart > preorder.length - 1 || inStart > inEnd){
return null;
}
int index = 0;
TreeNode root = new TreeNode(preorder[preStart]);
for(int i = inStart; i <= inEnd; i++){
if(inorder[i] == root.val){
index = i;
break;
}
}
root.left = helper(preStart + 1, inStart, index - 1, preorder, inorder);
root.right = helper(preStart + index - inStart + 1, index + 1, inEnd, preorder, inorder);
return root;
}
}