forked from atilsamancioglu/DA2-InterviewChallengeSolutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvertbsttogreatertree.py
36 lines (27 loc) · 1.17 KB
/
convertbsttogreatertree.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
'''
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.
'''
# 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 convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
sumOfValues = 0
def traversal(node):
if not node:
return
nonlocal sumOfValues
traversal(node.right)
temp = node.val
node.val += sumOfValues
sumOfValues += temp
traversal(node.left)
traversal(root)
return root