-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST to Greater Sum Tree.py
37 lines (25 loc) · 1004 Bytes
/
BST to Greater Sum Tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Link: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
total = 0
# Define a function for traversing
def adding(currNode):
# Override "total" from outside function
nonlocal total
if currNode == None:
return
# Traverse right side
adding(currNode.right)
# Update total and save value to current node to save time
total += currNode.val
currNode.val = total
# Traverse left side
adding(currNode.left)
adding(root)
return root