Skip to content

Commit ccfe76e

Browse files
committed
Runtime: 22 ms (Top 13.1%) | Memory: 13.44 MB (Top 40.5%)
1 parent 4388f75 commit ccfe76e

File tree

1 file changed

+23
-25
lines changed

1 file changed

+23
-25
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,24 @@
1-
# Definition for a binary tree node.
2-
# class TreeNode:
3-
# def __init__(self, val=0, left=None, right=None):
4-
# self.val = val
5-
# self.left = left
6-
# self.right = right
7-
class Solution:
8-
def increasingBST(self, root: TreeNode) -> TreeNode:
9-
def inorder(root,a):
10-
if root:
11-
inorder(root.left,a)
12-
a.append(root.val)
13-
inorder(root.right,a)
1+
# Runtime: 22 ms (Top 13.1%) | Memory: 13.44 MB (Top 40.5%)
2+
3+
class Solution(object):
4+
5+
def increasingBST(self, root):
146

15-
a=[]
16-
inorder(root,a)
17-
p1=TreeNode()
18-
tmp=p1
19-
for i in range(len(a)):
20-
if i==len(a)-1:
21-
p1.val=a[i]
22-
else:
23-
p1.val=a[i]
24-
p1.right=TreeNode()
25-
p1=p1.right
26-
return tmp
7+
def sortBST(node):
8+
if not node: return []
9+
10+
# return the in order BST nodes in list
11+
return sortBST(node.left) + [node.val] + sortBST(node.right)
12+
13+
# the in order sorted list of the tree nodes
14+
sorted_list = sortBST(root)
15+
16+
# generate new tree: temp for update, ans for return the root
17+
ans = temp = TreeNode(sorted_list[0])
18+
19+
# insert nodes to the right side of the new tree
20+
for i in range(1, len(sorted_list)):
21+
temp.right = TreeNode(sorted_list[i])
22+
temp = temp.right
23+
24+
return ans

0 commit comments

Comments
 (0)