コード例 #1
0
"""
Write a function to check if two trees have the same structure and the same elements.
"""

from implementations.tree import BinaryTreeNode


def equal(tree1, tree2):
    if tree1 is None and tree2 is None:
        return True
    elif tree1 is None or tree2 is None:
        return False
    return tree1.value == tree2.value and equal(tree1.left, tree2.left) and equal(tree1.right, tree2.right)


if __name__ == "__main__":
    tree1 = BinaryTreeNode(4)
    tree1.left = BinaryTreeNode(2)
    tree1.left.left = BinaryTreeNode(1)
    tree1.right = BinaryTreeNode(7)
    tree1.right.left = BinaryTreeNode(6)
    tree1.right.right = BinaryTreeNode(9)
    tree2 = BinaryTreeNode(4)
    tree2.left = BinaryTreeNode(2)
    tree2.left.left = BinaryTreeNode(1)
    tree2.right = BinaryTreeNode(7)
    tree2.right.left = BinaryTreeNode(6)
    tree2.right.right = BinaryTreeNode(9)
    print equal(tree1, tree2)
コード例 #2
0
from implementations.tree import BinaryTreeNode


def binary_tree_paths(root):
    return list(_binary_tree_paths(root))


def _binary_tree_paths(root):
    if root.left:
        for path in _binary_tree_paths(root.left):
            yield '%s->%s' % (root.value, path)
    if root.right:
        for path in _binary_tree_paths(root.right):
            yield '%s->%s' % (root.value, path)
    if root.left is None and root.right is None:
        yield root.value



if __name__ == '__main__':
    tree = BinaryTreeNode(4)
    tree.left = BinaryTreeNode(2)
    tree.left.left = BinaryTreeNode(1)
    tree.right = BinaryTreeNode(7)
    tree.right.left = BinaryTreeNode(6)
    tree.right.right = BinaryTreeNode(9)
    print binary_tree_paths(tree)
コード例 #3
0
ファイル: maximum_depth.py プロジェクト: rvitale/exercises
"""
from implementations.tree import BinaryTreeNode


def max_depth(tree):
    if not tree:
        return 0
    stack = [(1, tree)]
    max_h = 1
    while stack:
        depth, node = stack.pop()
        if node.left:
            stack.append((depth + 1, node.left))
        if node.right:
            stack.append((depth + 1, node.right))
        if depth > max_h:
            max_h = depth

    return max_h


if __name__ == '__main__':
    t = BinaryTreeNode(5)
    t.left = BinaryTreeNode(2)
    t.right = BinaryTreeNode(3)
    t.left.left = BinaryTreeNode(9)
    t.left.left.left = BinaryTreeNode(12)
    t.right.left = BinaryTreeNode(-1)
    t.right.right = BinaryTreeNode(10)
    print max_depth(t)