Friday, March 1, 2013

[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal

Thought:
Basically the Same with the previous problem
 
Code:
public class Solution {   
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int len = inorder.length;
        if(len == 0) return null;
        TreeNode root = new TreeNode(preorder[0]);
        int i = 0;
        for(i = 0; i < len; i ++) {
            if(inorder[i] == preorder[0]) break;
        }      
        root.left = buildTree(Arrays.copyOfRange(preorder, 1, i + 1), Arrays.copyOfRange(inorder, 0, i));
        root.right = buildTree(Arrays.copyOfRange(preorder, i + 1, len), Arrays.copyOfRange(inorder, i + 1, len));
        return root;
    }
}

No comments:

Post a Comment