Print Tree Level By Level

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


def print_tree_level_by_level(root):
    if not root:
        print 'Tree is empty'
        return

    queue = [root, None]

    while queue:
        curr = queue.pop(0)

        if curr:
            print '{}  '.format(curr.val),

            if curr.left:
                queue.append(curr.left)
            if curr.right:
                queue.append(curr.right)
        else:
            print
            if queue:
                queue.append(None)

Note:

  • Time complexity = O(n), n is the number of the nodes of the given tree.

results matching ""

    No results matching ""