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

lintcode-medium-Construct Binary Tree from Inorder and Postorder Traversal

时间:2016-03-16 12:15:16      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Given inorder [1,2,3] and postorder [1,3,2], return a tree:

  2
 / 1   3

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 
 
public class Solution {
    /**
     *@param inorder : A list of integers that inorder traversal of a tree
     *@param postorder : A list of integers that postorder traversal of a tree
     *@return : Root of a tree
     */
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        // write your code here
        
        if(inorder == null || inorder.length == 0)
            return null;
        
        int size = inorder.length;
        
        TreeNode root = build(inorder, 0, size - 1, postorder, 0, size - 1);
        
        return root;
    }
    
    public TreeNode build(int[] inorder, int in_start, int in_end, int[] postorder, int post_start, int post_end){
        
        if(in_start > in_end || post_start > post_end)
            return null;
        
        TreeNode root = new TreeNode(postorder[post_end]);
        
        int k = in_start;
        for(; k < in_end; k++){
            if(inorder[k] == postorder[post_end])
                break;
        }
        
        TreeNode left = build(inorder, in_start, k - 1, postorder, post_start, post_start + k - 1 - in_start);
        TreeNode right = build(inorder, k + 1, in_end, postorder, post_start + k - in_start, post_end - 1);
        
        root.left = left;
        root.right = right;
        
        return root;
    }
    
}

 

lintcode-medium-Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5282824.html

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