Notes
All notes

Trees (LeetCode #7)

A binary tree is a hierarchy: each node has up to two children, left and right. Almost every tree problem is the same recursion — “solve my left subtree, solve my right subtree, combine here” — or a breadth-first level sweep. This post covers all 15 NeetCode Tree problems.

The technique

A node holds a value and two children (either may be None):

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

DFS recursion returns a value up the tree:

def solve(node):
    if not node:
        return base                  # value for an empty subtree
    left = solve(node.left)
    right = solve(node.right)
    return combine(left, right, node.val)

Level-order BFS uses a queue and processes one level at a time; len(q) snapshots the level size.

BST property. For every node, all values in the left subtree are smaller and all in the right are larger. An inorder traversal of a BST is sorted.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\bfseries, inner sep=0pt},
  a/.style={->, thick}]
  \node[n, fill=orange!28] (r) at (0,0) {8};
  \node[n, fill=blue!12] (l) at (-1.5,-1.0) {3};
  \node[n, fill=blue!12] (rr) at (1.5,-1.0) {10};
  \node[n, fill=green!16] (ll) at (-2.2,-2.0) {1};
  \node[n, fill=green!16] (lr) at (-0.8,-2.0) {6};
  \draw[a] (r) -- (l); \draw[a] (r) -- (rr);
  \draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.6) {inorder = 1 3 6 8 10: sorted};
\end{tikzpicture}

Invert Binary Tree

The question. Mirror the tree: swap every node’s left and right children.

Input:   4             Output:   4
        / \                     / \
       2   7                   7   2

The idea. Invert the left subtree, invert the right subtree, then swap them. Recursion does the rest.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\bfseries, inner sep=0pt},
  a/.style={->, thick}]
  \node[n, fill=blue!10] (r) at (0,0) {4};
  \node[n, fill=blue!10] (l) at (-1.1,-1.0) {2}; \node[n, fill=blue!10] (rr) at (1.1,-1.0) {7};
  \draw[a] (r) -- (l); \draw[a] (r) -- (rr);
  \draw[<->, very thick, orange!80!black] (-1.1,-1.35) to[bend right=25] (1.1,-1.35);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.9) {swap children at every node};
\end{tikzpicture}
def invert(node):
    if not node:
        return None
    node.left, node.right = invert(node.right), invert(node.left)
    return node

\(O(n)\) time, \(O(h)\) space.

Maximum Depth of Binary Tree

The question. Return the number of nodes on the longest root-to-leaf path.

def max_depth(node):
    if not node:
        return 0
    return 1 + max(max_depth(node.left), max_depth(node.right))

\(O(n)\) time, \(O(h)\) space.

Diameter of Binary Tree

The question. Return the length of the longest path between any two nodes (in edges).

Input:   1            longest path 4->2->1->3 has 3 edges
        / \
       2   3
      / \
     4   5

The idea. The longest path through a node is left_height + right_height (a path that bends at that node). Track the best such value globally while returning the node’s height.

Walk it through on the tree above: node 2 has left height 1 and right height 1 → bend = 2; node 1 has left height 2 and right height 1 → bend = 3. Best is 3.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\bfseries, inner sep=0pt}]
  \node[n, fill=blue!10] (r) at (0,0) {1};
  \node[n, fill=orange!25] (l) at (-1.5,-1.1) {2}; \node[n, fill=blue!10] (rr) at (1.5,-1.1) {3};
  \node[n, fill=blue!10] (ll) at (-2.2,-2.2) {4}; \node[n, fill=blue!10] (lr) at (-0.8,-2.2) {5};
  \draw[thick] (r) -- (l); \draw[thick] (r) -- (rr); \draw[thick] (l) -- (ll); \draw[thick] (l) -- (lr);
  \draw[very thick, green!55!black, rounded corners=3pt] (ll) -- (l) -- (r) -- (rr);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.75) {the best path bends at a node: left + right};
\end{tikzpicture}
def diameter(root):
    best = 0
    def height(node):
        nonlocal best
        if not node:
            return 0
        l, r = height(node.left), height(node.right)
        best = max(best, l + r)        # path through this node
        return 1 + max(l, r)
    height(root)
    return best

\(O(n)\) time, \(O(h)\) space. Note this counts edges, not nodes.

Balanced Binary Tree

The question. Return True if every node’s subtrees differ in height by at most 1.

The idea. Compute heights bottom-up, but signal imbalance with a sentinel (-1) to stop early instead of recomputing heights.

def is_balanced(root):
    def check(node):
        if not node:
            return 0
        l, r = check(node.left), check(node.right)
        if l == -1 or r == -1 or abs(l - r) > 1:
            return -1                  # unbalanced sentinel
        return 1 + max(l, r)
    return check(root) != -1

\(O(n)\) time, \(O(h)\) space.

Same Tree

The question. Return True if two trees are identical in structure and values.

def is_same(p, q):
    if not p and not q:
        return True
    if not p or not q or p.val != q.val:
        return False
    return is_same(p.left, q.left) and is_same(p.right, q.right)

\(O(n)\) time.

Subtree of Another Tree

The question. Return True if sub is a subtree of root.

The idea. Walk every node of root; at each, check whether the subtree rooted there is identical to sub (reusing Same Tree).

def is_subtree(root, sub):
    if not sub:
        return True
    if not root:
        return False
    if is_same(root, sub):
        return True
    return is_subtree(root.left, sub) or is_subtree(root.right, sub)

\(O(n \cdot m)\) worst case, \(O(h)\) space.

Lowest Common Ancestor of a BST

The question. Return the lowest common ancestor of two nodes in a BST.

The idea. Use the BST order: if both targets are smaller than the current node, go left; if both larger, go right; otherwise the current node is the split point — the LCA.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\bfseries, inner sep=0pt},
  a/.style={->, thick}]
  \node[n, fill=orange!25] (r) at (0,0) {6};
  \node[n, fill=blue!10] (l) at (-1.5,-1.1) {2}; \node[n, fill=blue!10] (rr) at (1.5,-1.1) {8};
  \node[n, fill=green!15] (ll) at (-2.2,-2.2) {0}; \node[n, fill=green!15] (lr) at (-0.8,-2.2) {4};
  \draw[a] (r) -- (l); \draw[a] (r) -- (rr);
  \draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
  \node[font=\scriptsize\ttfamily, text=green!45!black, anchor=north] at (-1.5,-2.75) {p=2, q=4 split here};
\end{tikzpicture}
def lca_bst(root, p, q):
    while root:
        if p.val < root.val and q.val < root.val:
            root = root.left
        elif p.val > root.val and q.val > root.val:
            root = root.right
        else:
            return root

\(O(h)\) time, \(O(1)\) space.

Binary Tree Level Order Traversal

The question. Return node values level by level.

The idea. A queue holds the frontier. Before processing a level, snapshot its size with len(q) — the queue then contains exactly the nodes of the current level, and any nodes appended during the level belong to the next one.

Walk it through on:

    3
   / \
  9  20
     / \
    15  7
level queue at start nodes popped (level) children appended
0 [3] 3 9, 20
1 [9, 20] 9, 20 15, 7
2 [15, 7] 15, 7 —

Result [[3], [9, 20], [15, 7]].

from collections import deque

def level_order(root):
    if not root:
        return []
    out, q = [], deque([root])
    while q:
        level = []
        for _ in range(len(q)):          # exactly this level
            node = q.popleft()
            level.append(node.val)
            if node.left:  q.append(node.left)
            if node.right: q.append(node.right)
        out.append(level)
    return out

Why range(len(q)) and not for node in q. Iterating the deque directly would also visit the children appended during the same loop, mixing two levels together. Freezing the count with len(q) draws a level boundary.

Complexity. \(O(n)\) time (each node entered and left once) and \(O(n)\) space (the widest level dominates the queue).

Edge cases. Empty tree → []. A single node → [[val]]. A skewed tree → many levels of one node.

Binary Tree Right Side View

The question. Return the value of the rightmost node on each level.

The idea. The rightmost node of a level is simply the last node we pop while processing that level. So reuse the level-order sweep and record the value of the final pop.

Walk it through on the same tree:

level order popped last (rightmost)
0 3 3
1 9, 20 20
2 15, 7 7

Result [3, 20, 7].

from collections import deque

def right_side_view(root):
    if not root:
        return []
    out, q = [], deque([root])
    while q:
        level_size = len(q)              # freeze the level boundary
        for i in range(level_size):
            node = q.popleft()
            if i == level_size - 1:      # last node of this level
                out.append(node.val)
            if node.left:  q.append(node.left)
            if node.right: q.append(node.right)
    return out

Why capture level_size. len(q) grows as children are appended mid-level, so it cannot be used both to bound the loop and to identify the last index. Storing it once up front makes i == level_size - 1 correctly mark the final node.

Complexity. \(O(n)\) time and \(O(n)\) space (the widest level on the queue).

Edge cases. Empty tree → []. A right-leaning tree makes every level a single node. A node with only a left child is still the rightmost of its level, and the code records it because it is the last pop.

Count Good Nodes in Binary Tree

The question. A node is good if its value is ≥ every value on the path from the root to it. Count them.

Input:   3
        / \
       1   4
      /   / \
     3   1   5
Output: 4

The idea. DFS carrying the maximum value seen so far along the path. A node is good if its value ≥ that maximum; then recurse with the updated maximum.

Walk it through. Root 3 (max 3) good. 1 good. 4 good. Node 3 (max 3) good. 1 (max 4) not. 5 (max 4) good → 4 good nodes.

def good_nodes(root):
    def dfs(node, max_so_far):
        if not node:
            return 0
        good = 1 if node.val >= max_so_far else 0
        max_so_far = max(max_so_far, node.val)
        return good + dfs(node.left, max_so_far) + dfs(node.right, max_so_far)
    return dfs(root, float("-inf"))

\(O(n)\) time, \(O(h)\) space.

Validate Binary Search Tree

The question. Return True if the tree is a valid BST.

The trap. Checking only left.val < node.val < right.val accepts invalid trees, because a value deep in the left subtree can exceed an ancestor. The check must carry a range (low, high) down.

def is_valid_bst(root, low=float("-inf"), high=float("inf")):
    if not root:
        return True
    if not (low < root.val < high):
        return False
    return (is_valid_bst(root.left, low, root.val) and
            is_valid_bst(root.right, root.val, high))

\(O(n)\) time, \(O(h)\) space. An alternative is to check that an inorder traversal is strictly increasing.

Kth Smallest Element in a BST

The question. Return the k-th smallest value in a BST.

The idea. An inorder traversal visits a BST in sorted order; stop at the k-th node. Use an explicit stack to avoid recursion and stop early.

Walk it through on this BST, with k = 2:

      3
     / \
    1   4
     \
      2

Inorder is 1, 2, 3, 4, so the answer is 2. The stack simulates the recursion: descend left pushing every node, then pop (visit) and move to the right child.

action stack k node visited
push 3, push 1 [3, 1] 2 —
pop 1, go right to 2 [3] 1 1
push 2 [3, 2] 1 —
pop 2 [3] 0 2 → return 2
def kth_smallest(root, k):
    stack = []
    node = root
    while node or stack:
        while node:
            stack.append(node); node = node.left
        node = stack.pop()
        k -= 1
        if k == 0:
            return node.val
        node = node.right

Why the explicit stack. Inorder is “left, node, right”. The inner while walks as far left as possible; popping then visits the smallest not-yet-visited node. Stopping at k == 0 avoids traversing the rest of the tree.

Complexity. \(O(h + k)\) time (descend to the leftmost leaf, then visit k nodes) and \(O(h)\) space.

Edge cases. k = 1 → the leftmost node. k = n → the rightmost. The tree has at least k nodes by the problem’s guarantee.

Construct Binary Tree from Preorder and Inorder Traversal

The question. Given preorder and inorder traversals, rebuild the tree.

The idea. The first value in preorder is the root. Find it in inorder; everything to its left is the left subtree, and to its right is the right subtree. Because preorder visits the root then the left subtree then the right, we can consume preorder values in order.

Walk it through on preorder=[3,9,20,15,7], inorder=[9,3,15,20,7]: root 3; inorder left [9], right [15,20,7]; preorder next 9 is the left child; then 20, and so on.

def build_tree(preorder, inorder):
    index = {val: i for i, val in enumerate(inorder)}
    self_pre = iter(preorder)
    def build(lo, hi):
        if lo > hi:
            return None
        root_val = next(self_pre)
        root = TreeNode(root_val)
        mid = index[root_val]
        root.left = build(lo, mid - 1)
        root.right = build(mid + 1, hi)
        return root
    return build(0, len(inorder) - 1)

\(O(n)\) time (the index map makes the split \(O(1)\)), \(O(n)\) space.

Binary Tree Maximum Path Sum

The question. Maximum sum along any path (a path bends at most once).

Input:     -10
          /   \
         9    20
             /  \
            15   7
Output: 42         (15 + 20 + 7)

The idea. For each node track two values: the best downward gain to return to the parent (node.val + max(left, right)), and the best overall path bending here (node.val + left + right). Clamp negative branches to 0.

Walk it through on:

   -10
   /  \
  9   20
     /  \
    15   7

Each row shows the node’s two children gains, the bend recorded there, the running best, and the downward gain returned to its parent:

node left gain right gain bend (val+l+r) best so far returned val+max(l,r)
9 0 0 9 9 9
15 0 0 15 15 15
7 0 0 7 15 7
20 15 7 42 42 35
-10 9 35 34 42 25

The maximum is 42, the path 15 → 20 → 7.

def max_path_sum(root):
    best = float("-inf")
    def gain(node):
        nonlocal best
        if not node:
            return 0
        left = max(gain(node.left), 0)     # ignore negatives
        right = max(gain(node.right), 0)
        best = max(best, node.val + left + right)
        return node.val + max(left, right)
    gain(root)
    return best

Why two values. A path may pass through a node and use both children, but a path returned to the parent can only continue in one direction, so the returned value uses max(left, right) while the global best uses left + right. Keeping both is what lets a single bottom-up pass find the optimum.

Why clamp at 0. max(gain, 0) discards a negative branch: extending a path into a negative subtree can only lower the sum, so it is always better to stop. When every value is negative, the clamp means best becomes the largest single node (the best path is just that node).

Complexity. \(O(n)\) time, \(O(h)\) space.

Edge cases. A single negative node → that node’s value (not 0). All-negative paths are handled by the clamp, because the bend records node.val + 0 + 0.

Serialize and Deserialize Binary Tree

The question. Encode a tree as a string and rebuild it exactly.

The idea. Write preorder with null for empty children; the decoder reads values in the same order, consuming left then right.

Walk it through on:

    1
   / \
  2   3
     / \
    4   5

Preorder visits 1, 2, null, null, 3, 4, null, null, 5, null, null, so the string is 1,2,null,null,3,4,null,null,5,null,null. The decoder pulls values one at a time: it reads 1, then recursively builds the left child from the next value 2 (whose children are the two nulls), then the right child from 3, and so on. Because the encoder always emits both children of a node, the decoder always knows how many values each subtree needs.

def serialize(root):
    out = []
    def pre(node):
        if not node:
            out.append("null"); return
        out.append(str(node.val))
        pre(node.left); pre(node.right)
    pre(root)
    return ",".join(out)

def deserialize(data):
    vals = iter(data.split(","))
    def build():
        v = next(vals)
        if v == "null":
            return None
        node = TreeNode(int(v))
        node.left = build()
        node.right = build()
        return node
    return build()

Why preorder plus null markers. Preorder alone is ambiguous (several trees share it), and null placeholders record the shape. The decoder consumes the stream left-to-right in exactly the order the encoder wrote it, so no lengths or extra metadata are needed.

Why an iterator. next(vals) pulls the next value regardless of how deep the recursion is, which keeps the decoder a simple recursive mirror of the encoder.

Complexity. \(O(n)\) time and space (each node contributes one value plus two children markers).

Edge cases. Empty tree → "null", which decodes back to None. Negative values work because they are parsed with int. Duplicate values are fine because only positions matter, not values.

Pitfalls

QQuestionSelf-check

What is the general shape of a tree recursion? Why must a BST validation carry a range?

ASolution

Solve the left and right subtrees, then combine at the node (with a None base case). A node’s value must be greater than every ancestor on the left and less than every ancestor on the right, so the permitted (low, high) interval must be passed down — checking only the immediate parent accepts invalid trees.

Next: Heap / Priority Queue (LeetCode #8) — the current extreme.