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

[leetcode] Construct Binary Tree from Preorder and Inorder Traversal

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

标签:style   blog   http   java   color   strong   

Given preorder and inorder 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-preorder-and-inorder-traversal/

 

思路:类似上题,从preorder入手找到根节点然后在中序中分辨左右子树。

  因为java不支持返回数组后面元素的地址,所以写起来不如C/C++优雅,需要传递一个范围或者要局部复制数组。

bubuko.com,布布扣
public class Solution {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (inorder.length == 0 || preorder.length == 0)
            return null;
        TreeNode res = build(preorder, 0, preorder.length, inorder, 0, inorder.length);
        return res;

    }

    private TreeNode build(int[] pre, int a, int b, int[] in, int c, int d) {
        if (b - a <= 0)
            return null;
        TreeNode root = new TreeNode(pre[a]);
        int idx = -1;
        for (int i = c; i < d; i++) {
            if (in[i] == pre[a])
                idx = i;
        }
        // use the len, not idx
        int len = idx - c;
        root.left = build(pre, a + 1, a + 1 + len, in, c, c + len);
        root.right = build(pre, a + 1 + len, b, in, c + 1 + len, d);
        return root;
    }

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

 

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

[leetcode] Construct Binary Tree from Preorder and Inorder Traversal

标签:style   blog   http   java   color   strong   

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

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