Exemplo n.º 1
0
def aux_create_bst(arr,l,r):
    if l > r:
        return None
    m = l + (r-l)/2
    
    root = BinaryTreeNode(arr[m])
    root.left = aux_create_bst(arr,l,m-1)
    
    root.right = aux_create_bst(arr,m+1,r)
    return root
def build_tree_helper(preorder, inorder, in_start, in_end):

    if (in_start > in_end):
        return None

    # Pich current node from Preorder traversal using
    # preIndex and increment preIndex
    tNode = BinaryTreeNode(preorder[build_tree.preindex])
    build_tree.preindex += 1

    # If this node has no children then return
    if in_start == in_end:
        return tNode

    # Else find the index of this node in Inorder traversal
    inIndex = search(inorder, in_start, in_end, tNode.val)

    # Using index in Inorder Traversal, construct left
    # and right subtrees
    tNode.left = build_tree_helper(preorder, inorder, in_start, inIndex - 1)
    tNode.right = build_tree_helper(preorder, inorder, inIndex + 1, in_end)

    return tNode
    """
Exemplo n.º 3
0
    ## preorder traversal
    if cur_dist in dist_nodes:
        dist_nodes[cur_dist].append(root.val)
    else:
        dist_nodes[cur_dist] = [root.val]

    find_columns_helper(root.left, dist_nodes, cur_dist - 1)
    find_columns_helper(root.right, dist_nodes, cur_dist + 1)


root = BinaryTreeNode(6)
node1 = BinaryTreeNode(3)
node2 = BinaryTreeNode(5)
node3 = BinaryTreeNode(9)

node2.right = node3
node1.left = node2
root.left = node1

node4 = BinaryTreeNode(2)
node5 = BinaryTreeNode(7)
node6 = BinaryTreeNode(4)

node4.left = node5
node4.right = node6
root.right = node4

bt = BinaryTree(root)
print root.level_order()
"""
print 'height of the tree:', root.height()