Skip to content

Commit c56c050

Browse files
authored
Merge pull request doocs#116 from Mrtj2016/dev
add the solution of 0889.
2 parents 516a05c + 8cf81c2 commit c56c050

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
## 根据前序和后序遍历构造二叉树
2+
### 题目描述
3+
4+
返回与给定的前序和后序遍历匹配的任何二叉树。
5+
6+
`pre``post` 遍历中的值是不同的正整数。
7+
8+
9+
示例 :
10+
```
11+
输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
12+
输出:[1,2,3,4,5,6,7]
13+
```
14+
15+
16+
提示:
17+
18+
- 1 <= pre.length == post.length <= 30
19+
- pre[] 和 post[] 都是 1, 2, ..., pre.length 的排列
20+
- 每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。
21+
22+
### 解法
23+
由前序可以知道哪个是根节点(第一个节点即为根节点),由后序可以知道根节点的子节点有哪些(根节点之前的节点都是其子节点),递归可求。
24+
25+
```python
26+
class Solution:
27+
def constructFromPrePost(self, pre, post):
28+
if pre:
29+
root = TreeNode(pre[0])
30+
if len(pre) == 1:
31+
return root
32+
else:
33+
for i in range(0, len(pre) - 1):
34+
if post[i] == pre[1]:
35+
root.left = self.constructFromPrePost(
36+
pre[1:i + 1 + 1], post[:i + 1])
37+
root.right = self.constructFromPrePost(
38+
pre[i + 1 + 1:], post[i + 1:-1])
39+
break
40+
return root
41+
else:
42+
return None
43+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
9+
class Solution:
10+
def constructFromPrePost(self, pre, post):
11+
"""
12+
:type pre: List[int]
13+
:type post: List[int]
14+
:rtype: TreeNode
15+
"""
16+
if pre:
17+
root = TreeNode(pre[0])
18+
if len(pre) == 1:
19+
return root
20+
else:
21+
for i in range(0, len(pre) - 1):
22+
if post[i] == pre[1]:
23+
root.left = self.constructFromPrePost(
24+
pre[1:i + 1 + 1], post[:i + 1])
25+
root.right = self.constructFromPrePost(
26+
pre[i + 1 + 1:], post[i + 1:-1])
27+
break
28+
return root
29+
else:
30+
return None

0 commit comments

Comments
 (0)