105. Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7



class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder == null || inorder == null || preorder.length == 0 || 
          inorder.length == 0 || preorder.length != inorder.length){
            return null;
        }
        return construct(preorder, inorder, 0, 0, inorder.length - 1);
    }
    private TreeNode construct(int[] preorder, int[] inorder, int preStart, 
                              int inStart, int inEnd){
        // BASE CASE 
        if(preStart > preorder.length || inStart > inEnd) return null;
        
        
        // recursion + induction rule 
        // find the size of left subtree 
        int i = inStart;
        while (i <= inEnd){
            if(inorder[i] == preorder[preStart]){
                break;
            }
            i++;
        }
        // root 
        TreeNode root = new TreeNode(preorder[preStart]);
        root.left = construct(preorder, inorder, preStart + 1, inStart, i -1);
        root.right = construct(preorder, inorder, preStart + (i - inStart + 1), i + 1, inEnd);
        return root;
    }
}

 

posted on 2018-11-09 10:35  猪猪&#128055;  阅读(122)  评论(0)    收藏  举报

导航