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.
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
// 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);
} from collections import deque
# all nodes at distance k from target: parent map, then BFS in three directions
def distance_k(root, target, k):
parent = {}
def link(node, par):
if node:
parent[node] = par
link(node.left, node)
link(node.right, node)
link(root, None)
q, seen = deque([target]), {target}
for _ in range(k): # one ring further per round
for _ in range(len(q)):
node = q.popleft()
for nxt in (node.left, node.right, parent[node]):
if nxt and nxt not in seen:
seen.add(nxt)
q.append(nxt)
return [node.val for node in q]
# good nodes: carry the largest ancestor value down
def good_nodes(root, max_above=float('-inf')):
if not root:
return 0
m = max(max_above, root.val)
return (root.val >= max_above) + good_nodes(root.left, m) + good_nodes(root.right, m) // all nodes at distance k from target: parent map, then BFS in three directions
void linkParents(TreeNode* node, TreeNode* par, unordered_map<TreeNode*, TreeNode*>& parent) {
if (!node) return;
parent[node] = par;
linkParents(node->left, node, parent);
linkParents(node->right, node, parent);
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
unordered_map<TreeNode*, TreeNode*> parent;
linkParents(root, nullptr, parent);
queue<TreeNode*> q;
unordered_set<TreeNode*> seen{target};
q.push(target);
for (int d = 0; d < k && !q.empty(); d++) { // one ring further per round
for (int i = q.size(); i > 0; i--) {
TreeNode* node = q.front(); q.pop();
for (TreeNode* next : {node->left, node->right, parent[node]})
if (next && seen.insert(next).second) q.push(next);
}
}
vector<int> res;
for (; !q.empty(); q.pop()) res.push_back(q.front()->val);
return res;
}
// good nodes: carry the largest ancestor value down
int goodNodes(TreeNode* root, int maxAbove = INT_MIN) {
if (!root) return 0;
int m = max(maxAbove, root->val);
return (root->val >= maxAbove) + goodNodes(root->left, m) + goodNodes(root->right, m);
} // all nodes at distance k from target: parent map, then BFS in three directions
function distanceK(root, target, k) {
const parent = new Map();
(function link(node, par) {
if (!node) return;
parent.set(node, par);
link(node.left, node);
link(node.right, node);
})(root, null);
let q = [target];
const seen = new Set([target]);
for (let d = 0; d < k && q.length; d++) { // one ring further per round
const next = [];
for (const node of q)
for (const nb of [node.left, node.right, parent.get(node)])
if (nb && !seen.has(nb)) { seen.add(nb); next.push(nb); }
q = next;
}
return q.map((node) => node.val);
}
// good nodes: carry the largest ancestor value down
function goodNodes(root, maxAbove = -Infinity) {
if (!root) return 0;
const m = Math.max(maxAbove, root.val);
return (root.val >= maxAbove ? 1 : 0) + goodNodes(root.left, m) + goodNodes(root.right, m);
} The variations
-
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.
-
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 -
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.