Leetcode 题目解析之 Construct Binary Tree from Preorder and Inorder T
【摘要】 Leetcode 题目解析之 Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
题目要求:根据前序遍历和中序遍历序列,构建二叉树。
- 前序遍历p:1 2 4 3 5 6
- 中序遍历i:4 2 1 5 3 6
1
/ \
2 3
/ / \
4 5 6
前序遍历p0是二叉树的根结点,1是i2,则:
- p1…2是1的左子树的前序遍历,i0…1是1的左子树的中序遍历
- p3…5是1的右子树的前序遍历,i3…5是1的右子树的中序遍历
- 递归
int p = 0;
int[] preorder;
int[] inorder;
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;
this.inorder = inorder;
return buildTree(0, preorder.length);
}
TreeNode buildTree(int start, int end) {
if (start >= end) {
return null;
}
TreeNode root = new TreeNode(preorder[p]);
int i;
for (i = start; i < end && preorder[p] != inorder[i]; i++)
;
p++;
root.left = buildTree(start, i);
root.right = buildTree(i + 1, end);
return root;
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)