8000 Create convert_bst_to_greater_tree.py · winggyn/LintCodeInPython@a48f441 · GitHub
[go: up one dir, main page]

Skip to content

Commit a48f441

Browse files
authored
Create convert_bst_to_greater_tree.py
1 parent f6573e5 commit a48f441

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

convert_bst_to_greater_tree.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# coding: utf-8
2+
3+
class Solution:
4+
"""
5+
@param: root: the root of binary tree
6+
@return: the new root
7+
"""
8+
def convertBST(self, root):
9+
# write your code here
10+
# print(root.val, root.left.val, root.right.val)
11+
# print(root.left.val, root.left.left.val, root.left.right.val)
12+
# 传进来的树可能不符合二叉搜索树的规则,但还是按规矩处理。
13+
# [1]
14+
# [2] [3]
15+
# [4] [5] [6] [7]
16+
#
17+
# [1] = [1] + ([3] + [6] + [7]) = 17
18+
# [3] = [3] + [7] = 10
19+
# [6] = [6] + [10](from [3]) = 16
20+
# [7] = 7
21+
# [2] = [2] + [5] + [17](from [1]) = 24
22+
# [4] = [4] + [24](from [2]) = 28
23+
# [5] = [5] + [17](from [1]) = 22
24+
# {17, 24, 10, 28, 22, 16, 7}
25+
'''
26+
# 先使用递归方法实现
27+
Solution._convert(root, [0]) # 使用list传引用简化代码
28+
return root
29+
'''
30+
# 非递归做法
31+
if root:
32+
sum_ = 0
33+
stack = []
34+
p = root
35+
while p or (len(stack) > 0):
36+
while p:
37+
stack.append(p)
38+
p = p.right
39+
p = stack[-1]
40+
stack.pop()
41+
p.val += sum_
42+
sum_ = p.val
43+
p = p.left
44+
return root
45+
46+
@staticmethod
47+
def _convert(root, sum_):
48+
if root:
49+
Solution._convert(root.right, sum_)
50+
root.val += sum_[0]
51+
sum_[0] = root.val
52+
Solution._convert(root.left, sum_)
53+
54+
# easy: http://lintcode.com/zh-cn/problem/convert-bst-to-greater-tree/

0 commit comments

Comments
 (0)
0