python - Building a Tree with inorder and preorder traversal in Python3.x -
i trying build tree using preorder , inorder traversals (list of ints). here have far:
def build(preorder, inorder, heap): # builds tree inorder , preorder traversal if len(preorder) == 0: return none root = preorder[0] # root first item in preorder k = root left_count = inorder[(k-1)] # number of items in left sub-tree left_inorder = inorder[0:left_count] left_preorder = preorder[1:1+left_count] right_inorder = inorder[1+left_count:] right_preorder = preorder[1+left_count:] return [root, build(left_preorder, left_inorder), build(right_preorder, right_inorder)]
i believe algorithm correct, although wrong.
my question - @ point insert items tree? have class written handle this, i'm not sure insert call, function operate recursively. suggestions how should insert nodes tree appreciated.
class heap: def __init__(self,the_heap): self.heap = the_heap def getchildren(self,value): n = self.heap.index(value) return self.heap[2*n+1],self.heap[2*n+2] # think ... def getparent(self,value): n = self.heap.index(value) if n == 0: return none return self.heap[math.floor(n-1/2.0) ] # think ... def traverse(self): #do traversal here visit each node in order want pass the_heap = heap(range(100)) print the_heap.getchildren(2) print the_heap.getparent(6)
something that?
Comments
Post a Comment