整理了python version的逻辑。做了一下简化

This commit is contained in:
Logen
2023-01-08 16:37:47 -06:00
parent a008a74069
commit aad6b8cee2
2 changed files with 15 additions and 16 deletions

View File

@ -23,7 +23,7 @@
* 111.二叉树的最小深度 * 111.二叉树的最小深度
![我要打十个](https://tva1.sinaimg.cn/large/008eGmZEly1gnadnltbpjg309603w4qp.gif) ![我要打十个](https://tva1.sinaimg.cn/large/008eGmZEly1gPnadnltbpjg309603w4qp.gif)

View File

@ -209,29 +209,28 @@ class Solution {
# self.right = right # self.right = right
class Solution: class Solution:
def __init__(self): def __init__(self):
self.pre = TreeNode() self.count = 0
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root == None:
return
''' '''
倒序累加替换: 倒序累加替换:
[2, 5, 13] -> [[2]+[1]+[0], [2]+[1], [2]] -> [20, 18, 13]
''' '''
self.traversal(root) # 右
return root self.convertBST(root.right)
def traversal(self, root: TreeNode) -> None:
# 因为要遍历整棵树,所以递归函数不需要返回值
# Base Case
if not root:
return None
# 单层递归逻辑:中序遍历的反译 - 右中左
self.traversal(root.right) # 右
# 中
# 中节点用当前root的值加上pre的值 # 中节点用当前root的值加上pre的值
root.val += self.pre.val # 中 self.count += root.val
self.pre = root
self.traversal(root.left) # 左 root.val = self.count
# 左
self.convertBST(root.left)
return root
``` ```
## Go ## Go