题目:原题链接(简单)
与题目1038相同
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|
Ans 1 (Python) | O(N)O(N)O(N) | O(1)O(1)O(1) | 76ms (87.34%) |
Ans 2 (Python) | O(N)O(N)O(N) | O(1)O(1)O(1) | 68ms (98.52%) |
解法一(反序中序遍历):
def __init__(self):self.total = 0def convertBST(self, root: TreeNode) -> TreeNode:def helper(node):if not node:return 0helper(node.right)self.total += node.valnode.val = self.totalhelper(node.left)helper(root)return root
解法二(解法一的优雅化):
def __init__(self):self.total = 0def convertBST(self, root: TreeNode) -> TreeNode:if root:self.convertBST(root.right)self.total += root.valroot.val = self.totalself.convertBST(root.left)return root