首页 > 其他 > 详细

106. Construct Binary Tree from Inorder and Postorder Traversal

时间:2016-05-18 09:07:09      阅读:135      评论:0      收藏:0      [点我收藏+]
    /*
     * 106. Construct Binary Tree from Inorder and Postorder Traversal
     * 11.21 By Mingyang 
     * Becuase k is not the length, it it need to -(inStart+1) to get the length
     * 需要注意的就是k不能作为postorder的index,必须加上距离才行
     */
    public TreeNode buildTree2(int[] inorder, int[] postorder) {
        int inStart = 0;
        int inEnd = inorder.length - 1;
        int postStart = 0;
        int postEnd = postorder.length - 1;
        return buildTree2(inorder, inStart, inEnd, postorder, postStart,postEnd);
    }
    public TreeNode buildTree2(int[] inorder, int inStart, int inEnd,int[] postorder, int postStart, int postEnd) {
        if (inStart > inEnd || postStart > postEnd)
            return null;
        int rootValue = postorder[postEnd];
        TreeNode root = new TreeNode(rootValue);
        int k = 0;
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == rootValue) {
                k = i;
                break;
            }
        }
        root.left = buildTree2(inorder, inStart, k - 1, postorder, postStart,
                postStart + k - (inStart + 1));
        // Becuase k is not the length, it it need to -(inStart+1) to get the length
        //k只是与inorder有关,不能拿来postorder来用,这样就不行了
        root.right = buildTree2(inorder, k + 1, inEnd, postorder, postStart + k - inStart, postEnd - 1);
        // postStart+k-inStart = postStart+k-(inStart+1) +1
        return root;
    }

 

106. Construct Binary Tree from Inorder and Postorder Traversal

原文:http://www.cnblogs.com/zmyvszk/p/5503923.html

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