1038. Binary Search Tree to Greater Sum Tree - English Version

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

Thank you, this was a big help!! Note, if you remove the "nonlocal sum" line on line 12 and define sum as self.sum = 0 on line 10 instead, performance goes from "faster than ~38% to faster than 99%. This removes the redefinition of the sum variable in the function. Of course you need to change all the sum variables to self.sum. btw, this is probably the best python lesson on recursion on all of youtube.

bryandotmee
Автор

Really nice explanation of recursion. Finally got a grasp of the topic!

crystalzoya
Автор

Wish I was as quick as you with recursion. Very nicely solved

abdullahfaizurrahman
Автор

DFS iterative solution:

def bstToGst(self, root: TreeNode) -> TreeNode:
total = 0
def dfs(root):
nonlocal total
if not root:
return root

stack = []
while stack or root:
while root:
stack.append(root)
root = root.right

root = stack.pop()
total += root.val
root.val = total
root = root.left
dfs(root)
return root

abdifatahmoh
Автор

class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
running_sum = 0
def helper(node):
nonlocal running_sum
if not node: return 0
helper(node.right)
running_sum += node.val
node.val = running_sum
helper(node.left)
helper(root)
return root

Runtime: 40 ms, faster than 24.27% of Python3 online submissions for Binary Search Tree to Greater Sum Tree.
Memory Usage: 13.8 MB, less than 78.13% of Python3 online submissions for Binary Search Tree to Greater Sum Tree.

aunnfriends