mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
add Python solution
This commit is contained in:
@ -397,6 +397,9 @@ public:
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Python
|
||||||
|
|
||||||
|
|
||||||
# 105.从前序与中序遍历序列构造二叉树
|
# 105.从前序与中序遍历序列构造二叉树
|
||||||
|
|
||||||
[力扣题目链接](https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
|
[力扣题目链接](https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
|
||||||
@ -650,6 +653,37 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Python
|
## Python
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
|
||||||
|
# 第一步: 特殊情况讨论: 树为空. 或者说是递归终止条件
|
||||||
|
if not postorder:
|
||||||
|
return
|
||||||
|
|
||||||
|
# 第二步: 后序遍历的最后一个就是当前的中间节点
|
||||||
|
root_val = postorder[-1]
|
||||||
|
root = TreeNode(root_val)
|
||||||
|
|
||||||
|
# 第三步: 找切割点.
|
||||||
|
root_index = inorder.index(root_val)
|
||||||
|
|
||||||
|
# 第四步: 切割inorder数组. 得到inorder数组的左,右半边.
|
||||||
|
left_inorder = inorder[:root_index]
|
||||||
|
right_inorder = inorder[root_index + 1:]
|
||||||
|
|
||||||
|
# 第五步: 切割postorder数组. 得到postorder数组的左,右半边.
|
||||||
|
# ⭐️ 重点1: 中序数组大小一定跟后序数组大小是相同的.
|
||||||
|
left_postorder = postorder[:len(left_inorder)]
|
||||||
|
right_postorder = postorder[len(left_inorder): len(postorder) - 1]
|
||||||
|
|
||||||
|
|
||||||
|
# 第六步: 递归
|
||||||
|
root.left = self.buildTree(left_inorder, left_postorder)
|
||||||
|
root.right = self.buildTree(right_inorder, right_postorder)
|
||||||
|
|
||||||
|
# 第七步: 返回答案
|
||||||
|
return root
|
||||||
|
```
|
||||||
|
|
||||||
105.从前序与中序遍历序列构造二叉树
|
105.从前序与中序遍历序列构造二叉树
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user