Skip to content

Commit 994d4d9

Browse files
committed
Runtime: 36 ms (Top 83.6%) | Memory: 16.39 MB (Top 54.5%)
1 parent ca3fc9b commit 994d4d9

File tree

1 file changed

+11
-38
lines changed

1 file changed

+11
-38
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,13 @@
1-
# Runtime: 69 ms (Top 6.93%) | Memory: 14.1 MB (Top 33.83%)
2-
class Solution:
3-
def bstToGst(self, root: TreeNode) -> TreeNode:
4-
'''
5-
Left - root - right : gives sorted ordering of nodes - O(n)
6-
Then find prefix sum of the sorted array from the right side - O(n)
7-
Then do binary search on inorder array and get the prefix sum - O(nlogn) since we do binary search for each node
8-
'''
9-
10-
#find the inorder traversal
11-
def inorder(node,arr):
12-
if not node: return
13-
14-
inorder(node.left,arr)
15-
arr.append(node.val)
16-
inorder(node.right,arr)
17-
18-
arr = []
19-
inorder(root,arr)
20-
n = len(arr)
21-
22-
#find the prefix sum
23-
prefix = [num for num in arr]
24-
i = n-2
25-
while i>=0:
26-
prefix[i] += prefix[i+1]
27-
i-=1
1+
# Runtime: 36 ms (Top 83.6%) | Memory: 16.39 MB (Top 54.5%)
282

29-
#do binary search and fill in the prefix sum for each node
30-
def fill(node):
31-
if not node: return
32-
33-
i = bisect_left(arr,node.val)
34-
node.val = prefix[i]
35-
36-
fill(node.right)
37-
fill(node.left)
38-
39-
fill(root)
3+
class Solution:
4+
def bstToGst(self, root):
5+
self.total = 0
6+
def dfs(n):
7+
if n:
8+
dfs(n.right)
9+
self.total += n.val
10+
n.val = self.total
11+
dfs(n.left)
12+
dfs(root)
4013
return root

0 commit comments

Comments
 (0)