Skip to content

Commit cdb23c0

Browse files
authored
Create 538. Convert BST to Greater Tree.py
1 parent 8b0b698 commit cdb23c0

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#
2+
3+
'''
4+
1. 아이디어 :
5+
- 합을 구하기 위한 bfs
6+
- 가장 작은 노드를 방문하기 위한 inorder
7+
8+
2. 시간복잡도 :
9+
O(n + n)
10+
11+
3. 자료구조/알고리즘 :
12+
bfs, inorder traversal
13+
14+
'''
15+
class Solution:
16+
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
17+
self.total = 0
18+
19+
def get_total(node):
20+
return node.val + get_total(node.left) + get_total(node.right) if node else 0
21+
22+
def recalculate(node):
23+
if not node:
24+
return
25+
26+
recalculate(node.left)
27+
original = node.val
28+
self.total -= original
29+
node.val += self.total
30+
recalculate(node.right)
31+
32+
self.total = get_total(root)
33+
recalculate(root)
34+
return root

0 commit comments

Comments
 (0)