码迷,mamicode.com
首页 > 其他好文 > 详细

106. Construct Binary Tree from Inorder and Postorder Traversal

时间:2016-03-14 07:09:20      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

 

Subscribe to see which companies asked this question

 
/**
 * 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[] inorder, int[] postorder) {
        HashMap<Integer, Integer> inorderIndex = new HashMap<Integer, Integer>(inorder.length);
        for(int i = 0; i< inorder.length; ++i)
        {
            inorderIndex.put(inorder[i], i);
        }
        return buildTree(inorder, 0, inorder.length, postorder, 0, postorder.length, inorderIndex);
    }
    
    private TreeNode buildTree(int[] inorder, int inorderFrom, int inorderTo, int[] postorder, int postOrderFrom, int postordeTo, HashMap<Integer, Integer> inorderIndex)
    {
        if(inorderFrom>=inorderTo || postOrderFrom>=postordeTo)
            return null;
            
        int rootValue = postorder[postordeTo - 1];
        TreeNode root = new TreeNode(rootValue);
        int rootIndex = inorderIndex.get(rootValue);
        
        root.left = buildTree(inorder, inorderFrom, rootIndex, 
                              postorder, postOrderFrom, postOrderFrom + (rootIndex - inorderFrom), 
                              inorderIndex);
        root.right = buildTree(inorder, rootIndex+1, inorderTo, 
                               postorder, postOrderFrom + (rootIndex - inorderFrom), postordeTo - 1,
                               inorderIndex);
        return root;
    }
}

 

 
 

106. Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/5274424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!