Monday, November 2, 2015

[leetcode]Construct Binary Tree from Inorder and Postorder Traversal

这题难就难在分段index是什么
要想仔细!!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    HashMap<Integer, Integer> rootIndex = new HashMap<Integer, Integer>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for (int i = 0; i < inorder.length; i++){
            rootIndex.put(inorder[i], i);
        }
        return buildTree_rec(0, inorder.length-1, 0, postorder.length-1, postorder);
    }
    
    private TreeNode buildTree_rec(int instart, int inend, 
                                   int poststart, int postend, 
                                   int[]postorder){
        if (poststart > postend) return null;
        int root_i = rootIndex.get(postorder[postend]);
        TreeNode root = new TreeNode(postorder[postend]);
        root.left = buildTree_rec(instart, root_i-1, poststart, poststart+(root_i-instart)-1,postorder);
        root.right = buildTree_rec(root_i+1, inend, poststart+(root_i-instart), postend-1, postorder);
        return root;
    }
}

No comments:

Post a Comment