From 91f3da4b43f44d60a0f7c60436ec30869788ec04 Mon Sep 17 00:00:00 2001 From: Logen <47022821+Logenleedev@users.noreply.github.com> Date: Fri, 13 Jan 2023 12:53:05 -0600 Subject: [PATCH] add Python solution --- ...序与后序遍历序列构造二叉树.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index f8109f85..c2b2872b 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -397,6 +397,9 @@ public: }; ``` +## Python + + # 105.从前序与中序遍历序列构造二叉树 [力扣题目链接](https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) @@ -650,6 +653,37 @@ class Solution { ``` ## 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.从前序与中序遍历序列构造二叉树