Trees & BST · Pattern 8 of 12

Child and ancestor handling: the tree as a graph

A node only knows its children. Record every node's parent first, then you can move in three directions (left, right, up) and run BFS from any node.

3 variations · 4 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Distance from a node that is not the root
  • Fire or infection that spreads to neighbours each second
  • A check that depends on all the ancestors of a node

The template

Child + Ancestor Handling
// all nodes at distance k from target: parent map, then BFS in three directions
List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
    Map<TreeNode, TreeNode> parent = new HashMap<>();
    linkParents(root, null, parent);
    Deque<TreeNode> q = new ArrayDeque<>();
    Set<TreeNode> seen = new HashSet<>();
    q.offer(target); seen.add(target);
    for (int d = 0; d < k && !q.isEmpty(); d++) {           // one ring further per round
        for (int i = q.size(); i > 0; i--) {
            TreeNode node = q.poll();
            for (TreeNode next : new TreeNode[]{node.left, node.right, parent.get(node)})
                if (next != null && seen.add(next)) q.offer(next);
        }
    }
    List<Integer> res = new ArrayList<>();
    for (TreeNode node : q) res.add(node.val);
    return res;
}
void linkParents(TreeNode node, TreeNode par, Map<TreeNode, TreeNode> parent) {
    if (node == null) return;
    parent.put(node, par);
    linkParents(node.left, node, parent);
    linkParents(node.right, node, parent);
}

// good nodes: carry the largest ancestor value down
int goodNodes(TreeNode root) { return good(root, Integer.MIN_VALUE); }
int good(TreeNode node, int maxAbove) {
    if (node == null) return 0;
    int m = Math.max(maxAbove, node.val);
    return (node.val >= maxAbove ? 1 : 0) + good(node.left, m) + good(node.right, m);
}

The variations

  1. 1Parent map, then BFS

    One DFS stores each node's parent. Then BFS from the target treats left, right and parent as neighbours; after k rounds the queue holds the answer.

  2. 2Spread from a node

    The same BFS from the starting node. Each round is one second (or one minute of fire); the answer is how many rounds it takes to reach every node.

    Now you solve
  3. 3Carry what the ancestors know

    When you only need something about the ancestors (their max, their sum), pass it down as a parameter. No parent map needed.

Mistakes to avoid

  • Forgetting the visited set: once you can go up, a node can walk back to the child it came from.
  • Burning tree: the answer is the number of BFS rounds that add new nodes, not the number of rounds the loop ran.
  • Infection problems give the start as a value: find that node first (or build an adjacency list by value).

Mark it done once you can write the template from memory and you have solved the worked examples yourself.