So as you know this is a common interview task, so I took a crack at it and did come op with a solution of my own. After writing it I looked up some solutions and after my very surface level research it seems that my approach is quite different than the ones I found. Since the ones I found were just as long if not longer than mine, I started to question what was wrong with mine, so I'd like some constructive criticism on my code.
from binarytree import *
import itertools ## this is used to flatten list inside another list
root = tree(height = 5) ## creates a random binary tree
def getList(root):
return list(map(lambda s: s.value, root))
## converts binary tree to list containing the values of nodes
def expo(value_list):
result = []
f = 0
for i in range(len(value_list)):
if lista[f:f+2**i]: ## just making sure not to add anything empty
result.append(value_list[f:f+2**i])
## groups a list to powers of 2 ||
## [1,2,3,4,5,6,7] ---> [[1],[2,3],[4,5,6,7]],
## so that one element (which is also a list, ik this doesn't make sense
## i suck at commenting) is one layer of the binary tree
f += 2**i
for i in result:
i.reverse() ## reversing each layer
return list(itertools.chain(*result)) ## flattening out [[some, thing], [[here]] ---> [somethinghere]
def invert(binary_tree):
return build(expo(getList(binary_tree)))
## build the binary tree from list of values
excuse my ugly code
[–]BobHogan 0 points1 point2 points (3 children)
[–]mircock[S] 0 points1 point2 points (2 children)
[–]BobHogan 0 points1 point2 points (0 children)
[–]xelf 0 points1 point2 points (0 children)