首页 > 其他 > 详细

LeetCode - Construct Binary Tree from Inorder and Postorder Traversal

时间:2016-01-10 11:45:25      阅读:222      评论: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.

思路:

递归,根节点是postorder的最后一个节点

package treetraversal;

public class ConstructBinaryTreeFromInorderAndPostorderTraversal {

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return construct(postorder, 0, postorder.length - 1, inorder, 0, inorder.length - 1);
    }
    
    private TreeNode construct(int[] postorder, int pstart, int pend, int[] inorder, int istart, int iend) {
        if (pstart > pend || istart > iend) return null;
        int rootVal = postorder[pend];
        int index = -1;
        for (int i = istart; i <= iend; ++i) {
            if (inorder[i] == rootVal) {
                index = i;
                break;
            }
        }
        
        TreeNode root = new TreeNode(rootVal);        
        root.left = construct(postorder, pstart, pstart + index - istart - 1, inorder, istart, index - 1);
        root.right = construct(postorder, pstart + index - istart, pend - 1, inorder, index + 1, iend);
        return root;
    }
    
}

 

LeetCode - Construct Binary Tree from Inorder and Postorder Traversal

原文:http://www.cnblogs.com/shuaiwhu/p/5118092.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!