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

[leetcode] Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-07-03 19:13:08      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   os   

 

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

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

https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

 

思路:递归求解,后序遍历可以获得根节点,然后根据根节点在中序排列中的位置分出左右子树。

 

bubuko.com,布布扣
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (postorder.length == 0 || inorder.length == 0)
            return null;
        TreeNode res = build(inorder, postorder, inorder.length);
        return res;
    }

    private TreeNode build(int[] in, int[] post, int len) {
        if (len <= 0)
            return null;
        TreeNode root = new TreeNode(post[len - 1]);
        int idx = -1;
        for (int i = 0; i < len; i++) {
            if (in[i] == post[len - 1])
                idx = i;
        }

        root.left = build(Arrays.copyOfRange(in, 0, idx), Arrays.copyOfRange(post, 0, idx), idx);
        root.right = build(Arrays.copyOfRange(in, idx + 1, len), Arrays.copyOfRange(post, idx, len - 1), len - 1 - idx);

        return root;
    }
    

    public static void main(String[] args) {
        new Solution().buildTree(new int[] { 9, 3, 15, 20, 7 }, new int[] { 9, 15, 7, 20, 3 });
    }
}
View Code

 

[leetcode] Construct Binary Tree from Inorder and Postorder Traversal,布布扣,bubuko.com

[leetcode] Construct Binary Tree from Inorder and Postorder Traversal

标签:style   blog   http   color   strong   os   

原文地址:http://www.cnblogs.com/jdflyfly/p/3821338.html

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