Skip to content

Commit aecb21d

Browse files
3460741663azl397985856
authored andcommitted
feat: 每日一题 2019-08-05 (azl397985856#92)
* 2019-08-05题解 * 2019-08-05 leetcode-105题解 * 2019-08-05 readme.md更新 * 2019-08-05 readme.md更新
1 parent 981d032 commit aecb21d

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

daily/2019-08-05.md

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# 毎日一题 - 105.从前序与中序遍历序列构造二叉树
2+
3+
## 信息卡片
4+
5+
* 时间:2019-08-05
6+
* 题目链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
7+
- tag:`Tree` `Array`
8+
## 题目描述
9+
```
10+
根据一棵树的前序遍历与中序遍历构造二叉树。
11+
12+
注意:
13+
你可以假设树中没有重复的元素。
14+
15+
例如,给出
16+
17+
前序遍历 preorder = [3,9,20,15,7]
18+
中序遍历 inorder = [9,3,15,20,7]
19+
返回如下的二叉树:
20+
21+
3
22+
/ \
23+
9 20
24+
/ \
25+
15 7
26+
```
27+
## 参考答案
28+
递归构造二叉树,时间复杂度O(n)
29+
>
30+
关键在于前序遍历和中序遍历的特性:
31+
* 前序遍历:根节点是首元素
32+
* 中序遍历:根节点左侧的值是其左子树,右侧的值是其右子树
33+
>
34+
因此,我们首先要得到从前序序列中获取根节点,然后遍历中序序列,找到根节点的位置,以此直到其左子树和右子树的范围。当我们得到其左子树之后,事情就开始重复了,我们仍然需要根据前序序列中找到这颗左子树的根节点,然后再根据中序序列得到这颗左子树根节点的左右子树,右子树同理。因此实际上就是个回溯。
35+
```c
36+
struct TreeNode* _buildTree(int* preorder, int* pindex, int* inorder, int inbegin, int inend)
37+
{
38+
if(inbegin>inend)//区间不存在,空树
39+
{
40+
return NULL;
41+
}
42+
struct TreeNode* root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
43+
root->val=preorder[*pindex];
44+
(*pindex)++;
45+
if(inbegin==inend)//区间只有一个结点,就是根结点
46+
{
47+
root->val=inorder[inbegin];
48+
root->left=NULL;
49+
root->right=NULL;
50+
return root;
51+
}
52+
//区间正常
53+
int rootindex=inbegin;
54+
while(rootindex<=inend)//用前序的根划分中序为两个子区间
55+
{
56+
if(inorder[rootindex]==root->val)
57+
{
58+
break;
59+
}
60+
else
61+
{
62+
++rootindex;
63+
}
64+
}
65+
//递归创建左子树
66+
root->left= _buildTree(preorder, pindex, inorder, inbegin, rootindex-1);
67+
//递归创建右子树
68+
root->right= _buildTree(preorder, pindex, inorder, rootindex+1, inend);
69+
return root;
70+
}
71+
```
72+
## 其他优秀解答
73+
74+
> 暂缺

daily/README.md

+8
Original file line numberDiff line numberDiff line change
@@ -192,8 +192,16 @@ tag: `几何`
192192

193193
时间:2019-07-30
194194

195+
### [105.从前序与中序遍历序列构造二叉树](./2019-08-05.md)
196+
197+
tag: `Tree` `Array`
198+
199+
时间:2019-08-05
200+
195201
### [771.jewels-and-stones](./2019-08-22.md)
196202

197203
tag:String` `Hash Table`
198204

199205
时间: 2019-08-22
206+
207+

0 commit comments

Comments
 (0)