Wednesday, November 7, 2012

[LeetCode] Construct binary tree from Inorder and Preorder

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

Java Code:

 
public TreeNode buildTree(int[] preorder, int[] inorder) {
         if(inorder.length != preorder.length || preorder.length == 0) return null; 
           
          return buildSubTree(inorder, 0, inorder.length-1, preorder, 0, inorder.length-1);
        
    }
    
     public TreeNode buildSubTree(int[] inorder, int begin, int end, int[] preorder, int s, int t) {
        
           TreeNode root = new TreeNode(preorder[s]);
           int pos = begin;
           
           for(int i = begin; i <= end; i++){
               if(inorder[i] == preorder[s]){
                   pos = i;
                   break;
               }
           }
              
           if(begin <= pos - 1) root.left = buildSubTree(inorder, begin, pos-1, preorder, s+1, s+pos-begin);
           
           if(pos+1 <= end) root.right = buildSubTree(inorder, pos+1, end, preorder, s + pos-begin+1, t);
           
           return root;
    }

No comments:

Post a Comment