您的位置:首页 > 其它

[leetcode] Construct Binary Tree from Preorder and Inorder Traversal

2014-07-02 23:33 393 查看
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++优雅,需要传递一个范围或者要局部复制数组。

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐