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

106. Construct Binary Tree from Inorder and Postorder Traversal

时间:2016-10-13 09:33:42      阅读:168      评论: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.

 

Hide Company Tags
 Microsoft
Show Tags
Hide Similar Problems
 
/**
 * 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) {
        return buildSubTree(0, postorder.length -1, postorder, inorder, 0, postorder.length-1);
    }
    public TreeNode buildSubTree(int postLeft, int postRight, int[] postorder, int[] inorder, int inLeft, int inRight){
        if(postRight < postLeft || inLeft > inRight) return null;
        int mid = inLeft;
        TreeNode root = new TreeNode(postorder[postRight]);
        while(mid <= inRight){
            if(postorder[postRight] == inorder[mid]){
                root.left = buildSubTree(postLeft, postRight+mid-inRight -1 , postorder, inorder, inLeft, mid-1);
                root.right = buildSubTree(postRight+mid-inRight, postRight -1, postorder, inorder, mid+1, inRight);
            }
            mid++;
        }
        return root;
    }
}

 

106. Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/joannacode/p/5955089.html

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