Skip to content

Latest commit

 

History

History
64 lines (60 loc) · 1.54 KB

105. Construct Binary Tree from Preorder and Inorder Traversal.md

File metadata and controls

64 lines (60 loc) · 1.54 KB

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
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return helper(preorder,inorder,0,inorder.length-1,0,preorder.length-1);   
    }
    public TreeNode helper(int[] preorder,int[] inorder, int inS,int inE,int pS,int pE){
        if(inE<inS) return null;
        int rootVal=preorder[pS];
        int rootIdx=-1;
        for(int i=0;i<inorder.length;i++){
            if(inorder[i]==rootVal){
                rootIdx=i;
                break;
            }
        }
        int ire = inE;
        int pls = pS+1;
        int ils = inS;
        int pre = pE;
        int irs = rootIdx+1;
        int ile = rootIdx-1;
        int ple = ile-ils+pls;
        int prs = ple+1;
        TreeNode root=new TreeNode(rootVal);
        root.left=helper(preorder,inorder,ils,ile,pls,ple);
        root.right=helper(preorder,inorder,irs,ire,prs,pre);
        return root;
    }
}  }
}