Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit aea616d

Browse files
committed
🐱(tree): 106. 从中序与后序遍历序列构造二叉树
1 parent d4f0b05 commit aea616d

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

docs/data-structure/tree/recursion/README.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,66 @@ class Solution(object):
117117
return root
118118
```
119119

120+
## 106. 从中序与后序遍历序列构造二叉树
121+
122+
[原题链接](https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)
123+
124+
### 思路
125+
126+
[105. 从前序与中序遍历序列构造二叉树](https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) 这道题一样的思路。
127+
128+
先看一下什么是中序遍历和后序遍历:
129+
130+
- 中序遍历:左节点 -> 根节点 -> 右节点
131+
- 后序遍历:左节点 -> 右节点 -> 根节点
132+
133+
我们可以得知:
134+
135+
- 在后序遍历中:最后一个节点为根节点
136+
- 在中序遍历中:根节点左侧为该树的左子树,右侧为该树的右子树
137+
138+
例如在例题中:
139+
140+
> 中序遍历 inorder = [9,3,15,20,7]
141+
> 后序遍历 postorder = [9,15,7,20,3]
142+
143+
后序遍历 `postorder` 最后一个节点 `3` 为该树的根节点,`inorder``3` 的左侧 `[9]` 是树的左子树,右侧 `[15, 20, 7]` 则是树的右子树。
144+
145+
所以可以把问题拆分为:
146+
147+
1. 找到树的根节点 `root`
148+
2. 构建该根节点的左子树
149+
3. 构建该根节点的右子树
150+
151+
```python
152+
# Definition for a binary tree node.
153+
# class TreeNode:
154+
# def __init__(self, x):
155+
# self.val = x
156+
# self.left = None
157+
# self.right = None
158+
159+
class Solution:
160+
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
161+
162+
if len(inorder) == 0:
163+
return None
164+
165+
# 后序遍历最后一个节点为根节点
166+
root = TreeNode(postorder[-1])
167+
168+
# 根节点在中序遍历中的位置
169+
index = inorder.index(postorder[-1])
170+
171+
# 构造左子树
172+
root.left = self.buildTree(inorder[:index], postorder[:index])
173+
174+
# 构造右子树
175+
root.right = self.buildTree(inorder[index+1:], postorder[index:len(postorder) - 1])
176+
177+
return root
178+
```
179+
120180
## 110. 平衡二叉树
121181

122182
[原题链接](https://leetcode-cn.com/problems/balanced-binary-tree/description/)

0 commit comments

Comments
 (0)