From 40f8230fd86b475e87d970f973042a2b4cbee613 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Tue, 9 May 2023 00:20:58 -0500 Subject: [PATCH] =?UTF-8?q?Update=200106.=E4=BB=8E=E4=B8=AD=E5=BA=8F?= =?UTF-8?q?=E4=B8=8E=E5=90=8E=E5=BA=8F=E9=81=8D=E5=8E=86=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit python 代码重复 --- ...序与后序遍历序列构造二叉树.md | 38 +------------------ 1 file changed, 2 insertions(+), 36 deletions(-) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index adb374f9..89afad08 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -400,8 +400,6 @@ public: }; ``` -## Python - # 105.从前序与中序遍历序列构造二叉树 @@ -657,38 +655,6 @@ 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.从前序与中序遍历序列构造二叉树 ```python @@ -717,7 +683,7 @@ class Solution: # 第六步: 递归 root.left = self.buildTree(preorder_left, inorder_left) root.right = self.buildTree(preorder_right, inorder_right) - + # 第七步: 返回答案 return root ``` @@ -749,7 +715,7 @@ class Solution: # 第六步: 递归 root.left = self.buildTree(inorder_left, postorder_left) root.right = self.buildTree(inorder_right, postorder_right) - + # 第七步: 返回答案 return root ```