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.

Solution:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
    }
    public TreeNode buildTree(int[] preorder, int l1, int r1, int[] inorder, int l2, int r2) {
        if(r1<l1) return null;
        TreeNode root = new TreeNode(preorder[l1]);
        int mid = l2;
        while(inorder[mid]!=root.val) mid++;
        root.left = buildTree(preorder, l1+1, l1+(mid-l2), inorder, l2, mid-1);
        root.right = buildTree(preorder, l1+(mid-l2)+1, r1, inorder, mid+1, r2);
        return root;
    }
}
comments powered by Disqus