Skip to content

Instantly share code, notes, and snippets.

@Helw150
Created October 24, 2017 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Helw150/b5c797185f83948c40e6b39923a4a303 to your computer and use it in GitHub Desktop.
Save Helw150/b5c797185f83948c40e6b39923a4a303 to your computer and use it in GitHub Desktop.
Array to Min-Heap with In-Order Traversal the same as the Array
# i/p = array of numbers
# create a binary tree such that each subtree is a min-heap and the inorder traversal // of the binary tree is same as the array provided
# [5, 7, 10, 8, 1, 4]
# 1
# / \
# 5 4
# \
# 7
# \
# 8
# /
# 10
#node createTree(int arr[]);
# 1, 1, 1, 1, 1, 3, 4, 5, 3, 1
class BinaryNode():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def createTree(array_version):
if array_version == None:
return None
else:
sorted_array = sorted(array_version)
min_node_in_array = BinaryNode(sorted_array[0])
index_of_min_node = array_version.index(min_node_in_array.val)
min_node_in_array.right = createTree(array_version[index_of_min_node+1:])
min_node_in_array.left = createTree(array_version[:index_of_min_node])
return min_node_in_array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment