Skip to content

Instantly share code, notes, and snippets.

@duanebester
Created October 21, 2020 23:07
Show Gist options
  • Save duanebester/94742b6fa61797096ff383c411edac38 to your computer and use it in GitHub Desktop.
Save duanebester/94742b6fa61797096ff383c411edac38 to your computer and use it in GitHub Desktop.
Python perfect binary tree
class Node:
def __init__(self, value):
self.value = value
self.left = self.right = None
# Build from last elem first.
# First decrement with right and then left.
def build_tree(height, post):
if height == 1:
return Node(post.pop())
node = Node(post.pop())
node.right = build_tree(height-1, post)
node.left = build_tree(height-1, post)
return node
# A utility function to query tree for node's value and return node's parent
def query_parent(node, num, parent=-1):
if node == None:
return
if (node.value == num):
return parent
else:
ql = query_parent(node.left, num, node.value)
qr = query_parent(node.right, num, node.value)
return ql or qr
def solution(h, q):
post = list(range(1, 2**h))
tree = build_tree(h, post)
find_parent = lambda q_val: query_parent(tree, q_val)
return map(find_parent, q)
print solution(3, [1, 4, 7]) #[3,6,-1]
print solution(3, [7, 3, 5, 1]) #[-1,7,6,3]
print solution(5, [19, 14, 28]) #[21,15,29]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment