sagelearnai

Trees (DFS & BFS)

Signal: the input is a TreeNode root; depth, paths, ancestors, ordering in a BST, level-by-level output, comparing subtrees.

Core idea: almost every tree problem is a traversal plus the right information flowing up or down:

  • Bottom-up (post-order): each call returns something about its subtree (height, sum, "is valid"), and the parent combines its children's answers. Most "max/min/diameter/balanced" problems.
  • Top-down (pre-order): pass state down (current path sum, allowed value range).
  • Level-order (BFS): a queue processes nodes level by level, for "per level", "minimum depth" and "right side view" questions.
8 3 10 1 6 14 pre-order 8 3 1 6 10 14 · in-order 1 3 6 8 10 14 (sorted for a BST)post-order 1 6 3 14 10 8 · level-order 8 | 3 10 | 1 6 14

Templates

python
# Bottom-up DFS: return info about the subtree
def height(node):
    if not node:
        return 0
    return 1 + max(height(node.left), height(node.right))

# Top-down DFS: pass constraints down
def valid(node, lo, hi):
    if not node: return True
    if not (lo < node.val < hi): return False
    return valid(node.left, lo, node.val) and valid(node.right, node.val, hi)

# BFS level order
from collections import deque
q = deque([root])
while q:
    for _ in range(len(q)):          # exactly one level
        node = q.popleft()
        ...
        if node.left:  q.append(node.left)
        if node.right: q.append(node.right)
The "global answer" trick

When the answer isn't what the recursion naturally returns (e.g., diameter, max path sum), return one thing (the best downward path) and update a separate global/nonlocal best with another (the path through this node).

Trees in the tests use LeetCode's level-order array format, e.g. [8, 3, 10, 1, 6, null, 14], which is converted to TreeNodes for you.

Problems

  1. Invert Binary Tree (Easy): Swap children at every node
  2. Maximum Depth of Binary Tree (Easy): 1 + max(depth(left), depth(right))
  3. Diameter of Binary Tree (Easy): Return height, update best with left+right
  4. Balanced Binary Tree (Easy): Return height, or -1 as an 'unbalanced' sentinel
  5. Same Tree (Easy): Compare roots, then recurse on both sides
  6. Symmetric Tree (Easy): Mirror check: outer pair and inner pair must match
  7. Subtree of Another Tree (Easy): At every node of root, run Same Tree against subRoot
  8. Path Sum (Easy): Subtract as you descend; check at leaves
  9. Lowest Common Ancestor of a BST (Medium): Walk down until p and q split
  10. Lowest Common Ancestor of a Binary Tree (Medium): Post-order: a node whose two sides each found one target is the LCA
  11. Binary Tree Level Order Traversal (Medium): BFS, processing len(queue) nodes per level
  12. Binary Tree Zigzag Level Order Traversal (Medium): Level-order BFS; reverse every other level
  13. Binary Tree Right Side View (Medium): Last node of each BFS level (or DFS right-first, first visit per depth)
  14. Count Good Nodes in Binary Tree (Medium): Carry the max seen so far down the path
  15. Validate Binary Search Tree (Medium): Pass (low, high) bounds down
  16. Kth Smallest Element in a BST (Medium): In-order traversal visits values in sorted order
  17. Construct Binary Tree from Preorder and Inorder Traversal (Medium): preorder[0] is the root; its inorder index splits left/right sizes
  18. Flatten Binary Tree to Linked List (Medium): For each node, splice its left subtree between it and its right subtree
  19. Binary Tree Maximum Path Sum (Hard): Return best downward gain; update best through node
  20. Serialize and Deserialize Binary Tree (Hard): Preorder with null markers is a complete, self-delimiting encoding
  21. Binary Tree Inorder Traversal (Easy): Iterative: go left as far as possible, pop, then go right
  22. Minimum Depth of Binary Tree (Easy): BFS. The first leaf you dequeue is the shallowest
  23. Convert Sorted Array to Binary Search Tree (Easy): Middle element is the root; recurse on halves
  24. Average of Levels in Binary Tree (Easy): Level-order BFS; sum / count per level
  25. Path Sum II (Medium): DFS with a path stack; copy it out at matching leaves
  26. Sum Root to Leaf Numbers (Medium): Carry cur*10 + val down; add it at leaves
  27. Populating Next Right Pointers in Each Node (Medium): Use the level above (already linked) to link the level below, O(1) space
  28. Delete Node in a BST (Medium): Leaf: drop. One child: splice. Two children: replace with successor (or predecessor)
  29. Insert into a Binary Search Tree (Medium): Walk down as in search; attach at the null spot
  30. House Robber III (Medium): Return (rob this, skip this) pairs bottom-up: tree DP
  31. All Nodes Distance K in Binary Tree (Medium): Add parent links → the tree is an undirected graph → BFS k steps from target
  32. Binary Search Tree Iterator (Medium): Controlled inorder: a stack holding the left spine
  33. Path Sum III (Medium): Prefix sums along the root path + hash map (Subarray Sum = K on a tree)
  34. Count Complete Tree Nodes (Easy): Equal left/right spine heights → perfect subtree → 2^h − 1 without visiting it