print left view of binary tree in python

Here's the code to print the left view of a binary tree in Python using recursion:

main.py
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def left_view(root, level, max_level):
    if root is None:
        return
    if max_level[0] < level:
        print(root.val)
        max_level[0] = level
    left_view(root.left, level + 1, max_level)
    left_view(root.right, level + 1, max_level)

def print_left_view(root):
    max_level = [0]
    left_view(root, 1, max_level)
480 chars
19 lines

The above code defines a TreeNode class to represent the binary tree. The left_view function recursively traverses the tree and prints the leftmost nodes at each level. The print_left_view function initializes the max_level list to zero and calls the left_view function with the root node of the tree.

gistlibby LogSnag