-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst_to_gst.py
More file actions
36 lines (24 loc) · 1.04 KB
/
bst_to_gst.py
File metadata and controls
36 lines (24 loc) · 1.04 KB
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
"""Description:
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
"""
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:
self.summ = 0
def reverse(node: TreeNode):
if not node:
return
reverse(node.right)
self.summ += node.val
node.val = self.summ
reverse(node.left)
reverse(root)
return root