2014年2月17日星期一

LeetCode - 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.

 /**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder==null || inorder==null || preorder.length!=inorder.length || preorder.length==0) {
            return null;
        }
        return build(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
    }
   
    public int find(int inorder[], int iS, int iE, int target) {
        for(int i=iS;i<=iE;i++) {
            if(inorder[i]==target) {
                return i;
            }
        }
        return -1;
    }
   
    public TreeNode build(int[] preorder, int pS, int pE, int[] inorder, int iS, int iE) {
        if(pS>pE || iS>iE) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[pS]);
        int mid = find(inorder, iS, iE, preorder[pS]);
        int leftSize = mid - iS;
        root.left = build(preorder, pS+1, pS+leftSize, inorder, iS, mid-1);
        root.right = build(preorder, pS+leftSize+1, pE, inorder, mid+1, iE);
        return root;
    }
}

没有评论:

发表评论