Search This Blog

Wednesday, December 26, 2012

LeetCode:Construct Binary Tree from Inorder and Postorder Traversal

Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder 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[] inorder, int[] postorder) {
        // Start typing your Java solution below
        // DO NOT write main() function
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0;i<inorder.length;i++)
            map.put(inorder[i],i);
        return buildTree(map,inorder,postorder,0,inorder.length-1,0,postorder.length-1);
        
    }
    
    public TreeNode buildTree(HashMap<Integer, Integer> map, int[] inorder, int[]postorder, int a, int b, int c, int d){
        if(b<a || d<c) return null;
        TreeNode root = new TreeNode(postorder[d]);
        int i = map.get(postorder[d]);
        root.left = buildTree(map, inorder, postorder, a,i-1, c,c+i-1-a);
        root.right = buildTree(map, inorder, postorder, i+1,b, d-b+i,d-1);
        return root;
    }
}

No comments: