Burning Tree
Burning Tree is a hard trees & bst problem solved with the child + ancestor handling pattern.
The best approach, one dfs (child + ancestor handling), runs in O(n) time and O(h) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from parent map + bfs up.
Problem
A fire starts at the node with value target. Each second it spreads to that node’s parent and children. Return the minimum time for the whole tree to burn.
Examples
Example 1
- Input
root = [1, 2, 3, 4, 5, null, 6], target = 4- Output
4- Why
- Second 1: 2. Second 2: 1 and 5. Second 3: 3. Second 4: 6.
Example 2
- Input
root = [1, 2, 3], target = 1- Output
1
Constraints
- The tree has
1to10^5nodes; target exists. - Fire spreads from a burning node to its parent and children each second.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 9 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
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
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Parent map + BFS | O(n) | O(n) |
| One DFS (child + ancestor handling) | O(n) | O(h) |
1Parent map + BFS
O(n)O(n)Record parents to treat the tree as an undirected graph. BFS from the target and count levels.
- Build a parent map and locate target.
- BFS over children and parent; count the levels after the first.
class Solution {
public static int minTime(TreeNode root, int target) {
Map<TreeNode, TreeNode> parent = new HashMap<>();
TreeNode src = null;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode n = q.poll();
if (n.val == target) src = n;
if (n.left != null) { parent.put(n.left, n); q.add(n.left); }
if (n.right != null) { parent.put(n.right, n); q.add(n.right); }
}
Set<TreeNode> burnt = new HashSet<>();
q.add(src);
burnt.add(src);
int time = -1;
while (!q.isEmpty()) {
time++;
for (int i = q.size(); i > 0; i--) {
TreeNode n = q.poll();
for (TreeNode nb : new TreeNode[] { n.left, n.right, parent.get(n) })
if (nb != null && burnt.add(nb)) q.add(nb);
}
}
return time;
}
}class Solution:
def minTime(self, root: Optional[TreeNode], target: int) -> int:
parent: Dict[TreeNode, TreeNode] = {}
src = None
q = deque([root])
while q:
n = q.popleft()
if n.val == target:
src = n
if n.left is not None:
parent[n.left] = n; q.append(n.left)
if n.right is not None:
parent[n.right] = n; q.append(n.right)
burnt = {src}
q.append(src)
time = -1
while q:
time += 1
for _ in range(len(q)):
n = q.popleft()
for nb in (n.left, n.right, parent.get(n)):
if nb is not None and nb not in burnt:
burnt.add(nb)
q.append(nb)
return timeclass Solution {
public:
static int minTime(TreeNode* root, int target) {
unordered_map<TreeNode*, TreeNode*> parent;
TreeNode* src = nullptr;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* n = q.front(); q.pop();
if (n->val == target) src = n;
if (n->left != nullptr) { parent[n->left] = n; q.push(n->left); }
if (n->right != nullptr) { parent[n->right] = n; q.push(n->right); }
}
unordered_set<TreeNode*> burnt;
q.push(src);
burnt.insert(src);
int time = -1;
while (!q.empty()) {
time++;
for (int i = q.size(); i > 0; i--) {
TreeNode* n = q.front(); q.pop();
TreeNode* par = parent.count(n) ? parent[n] : nullptr;
for (TreeNode* nb : { n->left, n->right, par })
if (nb != nullptr && burnt.insert(nb).second) q.push(nb);
}
}
return time;
}
};function minTime(root, target) {
const parent = new Map();
let src = null;
let q = [root];
let head = 0;
while (head < q.length) {
const n = q[head++];
if (n.val === target) src = n;
if (n.left !== null) { parent.set(n.left, n); q.push(n.left); }
if (n.right !== null) { parent.set(n.right, n); q.push(n.right); }
}
const burnt = new Set();
q = [src];
burnt.add(src);
let time = -1;
while (q.length > 0) {
time++;
const next = [];
for (const n of q) {
for (const nb of [n.left, n.right, parent.get(n)])
if (nb != null && !burnt.has(nb)) { burnt.add(nb); next.push(nb); }
}
q = next;
}
return time;
}2One DFS (child + ancestor handling)
O(n)O(h)Return subtree height normally, but a negative distance when the subtree contains the target. At each ancestor, the fire reaches the far side after (distance to target) + (height of the other subtree) seconds. At the target itself, the answer is its own height below.
- At the target: best = max(best, height below); return -1.
- Ancestor with a negative side: best = max(best, dist + other height); return -(dist + 1).
- Otherwise return 1 + max(l, r).
class Solution {
private static int best;
public static int minTime(TreeNode root, int target) {
best = 0;
dfs(root, target);
return best;
}
private static int dfs(TreeNode n, int target) {
if (n == null) return 0;
int l = dfs(n.left, target), r = dfs(n.right, target);
if (n.val == target) {
best = Math.max(best, Math.max(l, r));
return -1;
}
if (l >= 0 && r >= 0) return 1 + Math.max(l, r);
int dist = -Math.min(l, r);
int other = l >= 0 ? l : r;
best = Math.max(best, dist + other);
return -(dist + 1);
}
}class Solution:
def minTime(self, root: Optional[TreeNode], target: int) -> int:
self.best = 0
self.dfs(root, target)
return self.best
def dfs(self, n: Optional[TreeNode], target: int) -> int:
if n is None:
return 0
l, r = self.dfs(n.left, target), self.dfs(n.right, target)
if n.val == target:
self.best = max(self.best, max(l, r))
return -1
if l >= 0 and r >= 0:
return 1 + max(l, r)
dist = -min(l, r)
other = l if l >= 0 else r
self.best = max(self.best, dist + other)
return -(dist + 1)class Solution {
private:
inline static int best;
public:
static int minTime(TreeNode* root, int target) {
best = 0;
dfs(root, target);
return best;
}
private:
static int dfs(TreeNode* n, int target) {
if (n == nullptr) return 0;
int l = dfs(n->left, target), r = dfs(n->right, target);
if (n->val == target) {
best = max(best, max(l, r));
return -1;
}
if (l >= 0 && r >= 0) return 1 + max(l, r);
int dist = -min(l, r);
int other = l >= 0 ? l : r;
best = max(best, dist + other);
return -(dist + 1);
}
};let best;
function minTime(root, target) {
best = 0;
dfs(root, target);
return best;
}
function dfs(n, target) {
if (n === null) return 0;
const l = dfs(n.left, target), r = dfs(n.right, target);
if (n.val === target) {
best = Math.max(best, Math.max(l, r));
return -1;
}
if (l >= 0 && r >= 0) return 1 + Math.max(l, r);
const dist = -Math.min(l, r);
const other = l >= 0 ? l : r;
best = Math.max(best, dist + other);
return -(dist + 1);
}Edge cases to test
- Target is the root
- Target is a leaf on the longest branch
Hints
Hint 1
Same problem as Amount of Time for Binary Tree to Be Infected: the answer is the farthest node's distance from the target.
FAQ
What is the best time complexity for Burning Tree?
One DFS (child + ancestor handling) runs in O(n) time and O(h) extra space.
Which pattern does Burning Tree use?
It is a trees & bst problem that uses the child + ancestor handling pattern. Other problems with the same pattern: Amount of Time for Binary Tree to Be Infected, All Nodes Distance K in Binary Tree, Count Good Nodes in Binary Tree.
Is there a brute force solution for Burning Tree?
Yes. Parent map + BFS takes O(n) time and O(n) space. Record parents to treat the tree as an undirected graph.
Which edge cases should I test for Burning Tree?
Target is the root; Target is a leaf on the longest branch.