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

105. Construct Binary Tree from Inorder and preorder Traversal

时间:2016-05-18 09:07:07      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

    /*
     * 105. Construct Binary Tree from Inorder and preorder Traversal 
     * 11.20 By Mingyang 
     * 千万不要以为root一定在中间那个点,还是要找一下中间点的位置
     * p.left = construct(preorder, preStart + 1, preStart + (k - inStart),inorder, inStart, k - 1);
     * p.right = construct(preorder, preStart + (k - inStart) + 1, preEnd,inorder, k + 1, inEnd);
     * 难点就在于如何找到这两个起点和终点的index
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int preEnd = preorder.length - 1;
        int inEnd = inorder.length - 1;
        return construct(preorder, 0, preEnd, inorder, 0, inEnd);
    }
    public TreeNode construct(int[] preorder, int preStart, int preEnd,int[] inorder, int inStart, int inEnd) {
        if (preStart > preEnd || inStart > inEnd) {
            return null;
        }
        int val = preorder[preStart];
        TreeNode p = new TreeNode(val);
        // find parent element index from inorder
        int k = 0;
        for (int i = 0; i < inorder.length; i++) {
            if (val == inorder[i]) {
                k = i;
                break;
            }
        }
        p.left = construct(preorder, preStart + 1, preStart + (k - inStart),inorder, inStart, k - 1);
        p.right = construct(preorder, preStart + (k - inStart) + 1, preEnd,inorder, k + 1, inEnd);
        return p;
    }

 

105. Construct Binary Tree from Inorder and preorder Traversal

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5503911.html

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