Nodes, children and None
A tree node in Python is an object with val, left and right. A missing child is None. The tree as a whole is a reference to its root. Trees are usually written level by level, left to right, with null for a gap, the way LeetCode does: [4, 2, 6, 1, 3, 5, 7] is the tree below. PyVisualizer builds the node objects from that list for you.
Traversal: left, node, right
An inorder traversal visits a node's whole left subtree, then the node, then its right subtree. Written recursively it is three lines, and the base case is an empty subtree (None), where there is nothing to do. On a binary search tree, like this one, inorder visits the values in sorted order.
The other two depth-first orders only move the middle line: preorder records the node before its subtrees, postorder after them.
def inorderTraversal(root):
result = []
def visit(node):
if node is None:
return
visit(node.left)
result.append(node.val)
visit(node.right)
visit(root)
return result
Depth: an answer built from the children
Many tree problems are answered bottom-up: ask both children, then combine. The maximum depth of a tree is 1 (the node itself) plus the larger of its children's depths, and an empty tree has depth 0. Each call returns its answer to its parent, so the leaves answer first and the root answers last.
def maxDepth(root):
if root is None:
return 0
left = maxDepth(root.left)
right = maxDepth(root.right)
return 1 + max(left, right)
What you see in PyVisualizer
A traversal like this one goes several calls deep, so it opens on the Recursion view: every visit call is a lane labelled with the node it was called on, and you can watch each one reach None and return. Switch to Memory to see the tree itself, with root and node labelled on the nodes they refer to, and result filling in, 1 to 7, beside it.
Common mistakes
- No check for None.
node.lefton a missing node raisesAttributeError: 'NoneType' object has no attribute 'left'. Handle the empty subtree first. - Dropping a child's answer. Calling
maxDepth(root.left)without using what it returns. - Confusing the input list with the tree. The level-order list is only a way to write the tree down; the code receives the root node, not the list.
Try it yourself
- Move the append in the traversal above the first visit call to get preorder, and compare the output.
- Give the depth example a lopsided tree such as [1, 2, null, 3, null, 4] and watch the calls go down one side.