-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathbst to min heap.py
91 lines (70 loc) · 1.82 KB
/
bst to min heap.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# C++ implementation to convert the
# given BST to Min Heap
# structure of a node of BST
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# function for the inorder traversal
# of the tree so as to store the node
# values in 'arr' in sorted order
def inorderTraversal(root, arr):
if root == None:
return
# first recur on left subtree
inorderTraversal(root.left, arr)
# then copy the data of the node
arr.append(root.data)
# now recur for right subtree
inorderTraversal(root.right, arr)
# function to convert the given
# BST to MIN HEAP performs preorder
# traversal of the tree
def BSTToMinHeap(root, arr, i):
if root == None:
return
# first copy data at index 'i' of
# 'arr' to the node
i[0] += 1
root.data = arr[i[0]]
# then recur on left subtree
BSTToMinHeap(root.left, arr, i)
# now recur on right subtree
BSTToMinHeap(root.right, arr, i)
# utility function to convert the
# given BST to MIN HEAP
def convertToMinHeapUtil(root):
# vector to store the data of
# all the nodes of the BST
arr = []
i = [-1]
# inorder traversal to populate 'arr'
inorderTraversal(root, arr);
# BST to MIN HEAP conversion
BSTToMinHeap(root, arr, i)
# function for the preorder traversal
# of the tree
def preorderTraversal(root):
if root == None:
return
# first print the root's data
print(root.data, end = " ")
# then recur on left subtree
preorderTraversal(root.left)
# now recur on right subtree
preorderTraversal(root.right)
# Driver Code
if __name__ == '__main__':
# BST formation
root = Node(4)
root.left = Node(2)
root.right = Node(6)
root.left.left = Node(1)
root.left.right = Node(3)
root.right.left = Node(5)
root.right.right = Node(7)
convertToMinHeapUtil(root)
print("Preorder Traversal:")
preorderTraversal(root)