-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode 897 - increasing order bst.py
31 lines (25 loc) · 1.03 KB
/
leetcode 897 - increasing order bst.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
# increasing order search tree | leetcode 897 | https://leetcode.com/problems/increasing-order-search-tree/
# rearrange a bst with each node having only a right child, and the originally left-most leaf as the new root
# method: inorder traversal to return sorted array, insert all elements as right child (since sorted array)
# 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 increasingBST(self, root):
self.inorderTrv = []
def inorder(root):
if root is None:
return None
inorder(root.left)
self.inorderTrv.append(root.val)
inorder(root.right)
inorder(root)
newRoot = TreeNode(self.inorderTrv[0])
toReturn = newRoot
for x in self.inorderTrv[1:]:
newRoot.right = TreeNode(x)
newRoot = newRoot.right
return toReturn