-
Notifications
You must be signed in to change notification settings - Fork 623
Expand file tree
/
Copy pathbt_to_bst.py
More file actions
42 lines (30 loc) · 767 Bytes
/
bt_to_bst.py
File metadata and controls
42 lines (30 loc) · 767 Bytes
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
32
33
34
35
36
37
38
39
40
41
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def store_inorder(root, inorder):
if root is None:
return
store_inorder(root.left, inorder)
inorder.append(root.data)
store_inorder(root.right, inorder)
def count_nodes(root):
if root is None:
return 0
return count_nodes(root.left) + count_nodes(root.right) + 1
def array_to_bst(arr, root):
if root is None:
return
array_to_bst(arr, root.left)
root.data = arr[0]
arr.pop(0)
array_to_bst(arr, root.right)
def bt_to_bst(root):
if root is None:
return
n = count_nodes(root)
arr = []
store_inorder(root, arr)
arr.sort()
array_to_bst(arr, root)