Minimum time to burn a Tree starting from a Leaf node
Last Updated :
12 Jul, 2025
Given a binary tree and a target node, determine the minimum time required to burn the entire tree if the target node is set on fire. In one second, the fire spreads from a node to its left child, right child, and parent.
Note: The tree contains unique values.
Examples:
Input: root[] = [1, 2, 3, 4, 5, 6, 7], target = 2
Output : 3
Explanation:
[Expected Approach] Using Queue - O(n) Time and O(n) Space
The idea is to map the child nodes to their parent nodes. Then traverse the tree from the target node using breadth first algorithm (BFS) and return the time required.
Step by step Implementation:
- Find the node having value = target using queue. At each node, if its value if equal to target, then set target node to it. Also if current node's left or right child exists, then map the children nodes to the parent node in a hash map.
- Initialize an empty queue and push the target node into it. Initialize the answer variable to -1 (It will return 0 if only the target node in present in tree).
- While queue is not empty.
- Find the size of the queue , say 's'. Pop 's' nodes in one iteration.
- For each node curr. Check if its left, right or parent node has been traversed yet. If they are not, then push them into the queue.
- After popping 's' elements, increment the answer.
- Return the answer.
C++
// C++ program to find the minimum time required
// to burn the complete binary tree
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* left, *right;
Node(int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
int minTime(Node *root, int target) {
// Base case
if (root == nullptr) return -1;
queue<Node*> q;
q.push(root);
Node* tar;
// hash map to map the child nodes
// to their parent nodes
unordered_map<Node*, Node*> par;
par[root] = nullptr;
while (!q.empty()) {
Node* curr = q.front();
q.pop();
// Set tar = curr if value
// is equal.
if (curr->data == target)
tar = curr;
// map the left child to its
// parent
if (curr->left != nullptr) {
par[curr->left] = curr;
q.push(curr->left);
}
// map the right child to its
// parent
if (curr->right != nullptr) {
par[curr->right] = curr;
q.push(curr->right);
}
}
// hash map to check if a node
// has been visited or not.
unordered_map<Node*, bool> vis;
int ans = -1;
q.push(tar);
while (!q.empty()) {
int size = q.size();
while (size--) {
Node* curr = q.front();
vis[curr] = true;
q.pop();
// Push the left child node.
if (curr->left != nullptr && !vis[curr->left])
q.push(curr->left);
// Push the right child node.
if (curr->right != nullptr && !vis[curr->right])
q.push(curr->right);
// Push the parent node.
if (par[curr] != nullptr && !vis[par[curr]])
q.push(par[curr]);
}
// increment the answer
ans++;
}
return ans;
}
int main() {
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
int target = 2;
cout << minTime(root, target) << endl;
return 0;
}
Java
// Java Program to find the minimum time
// required to burn the complete binary tree
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
static int minTime(Node root, int target) {
// Base case
if (root == null)
return -1;
Queue<Node> q = new LinkedList<>();
q.add(root);
Node tar = null;
// HashMap to map the child nodes to
// their parent nodes
Map<Node, Node> par = new HashMap<>();
par.put(root, null);
while (!q.isEmpty()) {
Node curr = q.poll();
// Set tar = curr if value is equal
if (curr.data == target)
tar = curr;
// Map the left child to its parent
if (curr.left != null) {
par.put(curr.left, curr);
q.add(curr.left);
}
// Map the right child to its parent
if (curr.right != null) {
par.put(curr.right, curr);
q.add(curr.right);
}
}
// HashMap to check if a node has
// been visited or not
Map<Node, Boolean> vis = new HashMap<>();
int ans = -1;
q.add(tar);
while (!q.isEmpty()) {
int size = q.size();
while (size-- > 0) {
Node curr = q.poll();
vis.put(curr, true);
// Push the left child node
if (curr.left != null
&& !vis.getOrDefault(curr.left, false))
q.add(curr.left);
// Push the right child node
if (curr.right != null
&& !vis.getOrDefault(curr.right, false))
q.add(curr.right);
// Push the parent node
if (par.get(curr) != null
&& !vis.getOrDefault(par.get(curr),
false))
q.add(par.get(curr));
}
// Increment the answer
ans++;
}
return ans;
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
int target = 2;
System.out.println(minTime(root, target));
}
}
Python
# Python Program to find the minimum time
# required to burn the complete binary tree
from collections import deque
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
def minTime(root, target):
# Base case
if root is None:
return -1
q = deque([root])
tar = None
# Dictionary to map child nodes to
# parent nodes
par = {root: None}
while q:
curr = q.popleft()
# Set tar = curr if value is equal
if curr.data == target:
tar = curr
# Map the left child to its parent
if curr.left:
par[curr.left] = curr
q.append(curr.left)
# Map the right child to its parent
if curr.right:
par[curr.right] = curr
q.append(curr.right)
# Dictionary to check if a node has
# been visited or not
vis = {}
ans = -1
q.append(tar)
while q:
size = len(q)
for _ in range(size):
curr = q.popleft()
vis[curr] = True
# Push the left child node
if curr.left and not vis.get(curr.left, False):
q.append(curr.left)
# Push the right child node
if curr.right and not vis.get(curr.right, False):
q.append(curr.right)
# Push the parent node
if par[curr] and not vis.get(par[curr], False):
q.append(par[curr])
# Increment the answer
ans += 1
return ans
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
target = 2
print(minTime(root, target))
C#
// C# Program to find the minimum time
// required to burn the complete binary tree
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
static int MinTime(Node root, int target) {
// Base case
if (root == null)
return -1;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
Node tar = null;
// Dictionary to map the child nodes
// to their parent nodes
Dictionary<Node, Node> par
= new Dictionary<Node, Node>();
par[root] = null;
while (q.Count > 0) {
Node curr = q.Dequeue();
// Set tar = curr if value is equal
if (curr.data == target)
tar = curr;
// Map the left child to its parent
if (curr.left != null) {
par[curr.left] = curr;
q.Enqueue(curr.left);
}
// Map the right child to its parent
if (curr.right != null) {
par[curr.right] = curr;
q.Enqueue(curr.right);
}
}
// Dictionary to check if a node has
// been visited or not
Dictionary<Node, bool> vis
= new Dictionary<Node, bool>();
int ans = -1;
q.Enqueue(tar);
while (q.Count > 0) {
int size = q.Count;
while (size-- > 0) {
Node curr = q.Dequeue();
vis[curr] = true;
// Push the left child node
if (curr.left != null
&& !vis.ContainsKey(curr.left))
q.Enqueue(curr.left);
// Push the right child node
if (curr.right != null
&& !vis.ContainsKey(curr.right))
q.Enqueue(curr.right);
// Push the parent node
if (par[curr] != null
&& !vis.ContainsKey(par[curr]))
q.Enqueue(par[curr]);
}
// Increment the answer
ans++;
}
return ans;
}
static void Main(string[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
int target = 2;
Console.WriteLine(MinTime(root, target));
}
}
JavaScript
// JavaScript Program to find the minimum time
// required to burn the complete binary tree
class Node {
constructor(x) {
this.key = x;
this.left = null;
this.right = null;
}
}
function minTime(root, target) {
// Base case
if (root === null) return -1;
let q = [];
q.push(root);
let tar = null;
// Map to store parent nodes
// of each child
let par = new Map();
par.set(root, null);
while (q.length > 0) {
let curr = q.shift();
// Set tar = curr if value is equal
if (curr.key === target)
tar = curr;
// Map the left child to its parent
if (curr.left !== null) {
par.set(curr.left, curr);
q.push(curr.left);
}
// Map the right child to its parent
if (curr.right !== null) {
par.set(curr.right, curr);
q.push(curr.right);
}
}
// Set to check if a node has
// been visited or not
let vis = new Set();
let ans = -1;
q.push(tar);
while (q.length > 0) {
let size = q.length;
while (size-- > 0) {
let curr = q.shift();
vis.add(curr);
// Push the left child node
if (curr.left !== null && !vis.has(curr.left))
q.push(curr.left);
// Push the right child node
if (curr.right !== null && !vis.has(curr.right))
q.push(curr.right);
// Push the parent node
if (par.get(curr) !== null && !vis.has(par.get(curr)))
q.push(par.get(curr));
}
// Increment the answer
ans++;
}
return ans;
}
class QueueNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
// O(1) enqueue and dequeue queue
class Queue {
constructor() {
this.front = this.rear = null;
}
enqueue(value) {
const node = new QueueNode(value);
if (this.rear) {
this.rear.next = node;
this.rear = node;
} else {
this.front = this.rear = node;
}
}
dequeue() {
if (!this.front) return null;
const temp = this.front;
this.front = this.front.next;
if (!this.front) this.rear = null;
return temp.value;
}
isEmpty() {
return this.front === null;
}
}
// Driver Code
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
// Target
let target = 2;
console.log(minTime(root, target));
[Alternate Approach] Using Recursion - O(n) Time and O(h) Space
The idea is to recursively traverse the tree to find the target node and calculate the maximum distance between the target node and the leaf nodes.
Recursively traverse the binary tree, for each node curr, there are four possiblities:
- If the curr node is equal to target node, then find the depth of its left and right subtree and compare it with answer. Return 1.
- If the target node is present in left subtree (answer returned by left is not equal to -1), then find the depth of right subtree and compare (distance of current node from target node + depth of right subtree) with the answer. Return 1 + left.
- If the target node is present in right subtree (answer returned by right is not equal to -1), then find the depth of left subtree and compare (distance of current node from target node + depth of left subtree) with the answer. Return 1 + right.
- If answer returned by left and right subtree is equal to -1, then it means target node is not present in this subtree. Return -1.
C++
// C++ program to find the minimum time required
// to burn the complete binary tree
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* left, *right;
Node(int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
// Function to find the depth
// from the root.
int findDepth(Node* root) {
if (root == nullptr) return 0;
int left = findDepth(root->left);
int right = findDepth(root->right);
return max(left,right)+1;
}
// This function return the distance of current
// node from the target node. Returns -1 if
// target node is not found.
int findTarNode(Node* root, int target, int &ans) {
// base case
if (root == nullptr)
return -1;
// if current node is the target, find the
// depth of root, compare it with ans and
// return 1.
if (root->data == target) {
int depth = findDepth(root)-1;
ans = max(ans, depth);
return 1;
}
int left = findTarNode(root->left, target, ans);
// If target node is found in the left subtree
// ,then compare the depth of right subtree and dis
// of target node with ans.
if (left != -1) {
int depth = findDepth(root->right);
ans = max(ans, left+depth);
return left+1;
}
// If target node is found in the right subtree
// ,then compare the depth of left subtree and dis
// of target node with ans.
int right = findTarNode(root->right, target, ans);
if (right != -1) {
int depth = findDepth(root->left);
ans = max(ans, right+depth);
return right+1;
}
// if target node is not found,
// return -1.
return -1;
}
int minTime(Node *root, int target) {
int ans = 0;
findTarNode(root, target, ans);
return ans;
}
int main() {
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
int target = 2;
cout << minTime(root, target) << endl;
return 0;
}
Java
// Java Program to find the minimum time
// required to burn the complete binary tree
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to find the depth
// from the root.
static int findDepth(Node root) {
if (root == null) return 0;
int left = findDepth(root.left);
int right = findDepth(root.right);
return Math.max(left, right) + 1;
}
// This function returns the distance of current
// node from the target node. Returns -1 if
// target node is not found.
static int findTarNode(Node root, int target, int[] ans) {
// base case
if (root == null) return -1;
// if current node is the target, find the
// depth of root, compare it with ans and
// return 1.
if (root.data == target) {
int depth = findDepth(root) - 1;
ans[0] = Math.max(ans[0], depth);
return 1;
}
int left = findTarNode(root.left, target, ans);
// If target node is found in the left subtree
// ,then compare the depth of right subtree and dis
// of target node with ans.
if (left != -1) {
int depth = findDepth(root.right);
ans[0] = Math.max(ans[0], left + depth);
return left + 1;
}
// If target node is found in the right subtree
// ,then compare the depth of left subtree and dis
// of target node with ans.
int right = findTarNode(root.right, target, ans);
if (right != -1) {
int depth = findDepth(root.left);
ans[0] = Math.max(ans[0], right + depth);
return right + 1;
}
// if target node is not found,
// return -1.
return -1;
}
static int minTime(Node root, int target) {
// Answer variable is represented
// as array to pass it by reference
int[] ans = {0};
findTarNode(root, target, ans);
return ans[0];
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
int target = 2;
System.out.println(minTime(root, target));
}
}
Python
# Python Program to find the minimum time
# required to burn the complete binary tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to find the depth
# from the root.
def findDepth(root):
if root is None:
return 0
left = findDepth(root.left)
right = findDepth(root.right)
return max(left, right) + 1
# This function returns the distance of current
# node from the target node. Returns -1 if
# target node is not found.
def findTarNode(root, target, ans):
# base case
if root is None:
return -1
# if current node is the target, find the
# depth of root, compare it with ans and
# return 1.
if root.data == target:
depth = findDepth(root) - 1
ans[0] = max(ans[0], depth)
return 1
left = findTarNode(root.left, target, ans)
# If target node is found in the left subtree
# ,then compare the depth of right subtree and dis
# of target node with ans.
if left != -1:
depth = findDepth(root.right)
ans[0] = max(ans[0], left + depth)
return left + 1
# If target node is found in the right subtree
# ,then compare the depth of left subtree and dis
# of target node with ans.
right = findTarNode(root.right, target, ans)
if right != -1:
depth = findDepth(root.left)
ans[0] = max(ans[0], right + depth)
return right + 1
# if target node is not found,
# return -1.
return -1
def minTime(root, target):
ans = [0]
findTarNode(root, target, ans)
return ans[0]
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
target = 2
print(minTime(root, target))
C#
// C# Program to find the minimum time
// required to burn the complete binary tree
using System;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to find the depth
// from the root.
static int findDepth(Node root) {
if (root == null) return 0;
int left = findDepth(root.left);
int right = findDepth(root.right);
return Math.Max(left, right) + 1;
}
// This function returns the distance of current
// node from the target node. Returns -1 if
// target node is not found.
static int findTarNode(Node root, int target, ref int ans) {
// base case
if (root == null) return -1;
// if current node is the target, find the
// depth of root, compare it with ans and
// return 1.
if (root.data == target) {
int depth = findDepth(root) - 1;
ans = Math.Max(ans, depth);
return 1;
}
int left = findTarNode(root.left, target, ref ans);
// If target node is found in the left subtree
// ,then compare the depth of right subtree and dis
// of target node with ans.
if (left != -1) {
int depth = findDepth(root.right);
ans = Math.Max(ans, left + depth);
return left + 1;
}
// If target node is found in the right subtree
// ,then compare the depth of left subtree and dis
// of target node with ans.
int right = findTarNode(root.right, target, ref ans);
if (right != -1) {
int depth = findDepth(root.left);
ans = Math.Max(ans, right + depth);
return right + 1;
}
// if target node is not found,
// return -1.
return -1;
}
static int minTime(Node root, int target) {
int ans = 0;
findTarNode(root, target, ref ans);
return ans;
}
static void Main() {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
int target = 2;
Console.WriteLine(minTime(root, target));
}
}
JavaScript
// JavaScript Program to find the minimum time
// required to burn the complete binary tree
class Node {
constructor(x) {
this.key = x;
this.left = null;
this.right = null;
}
}
// Function to find the depth
// from the root.
function findDepth(root) {
if (root === null) return 0;
let left = findDepth(root.left);
let right = findDepth(root.right);
return Math.max(left, right) + 1;
}
// This function returns the distance of current
// node from the target node. Returns -1 if
// target node is not found.
function findTarNode(root, target, ans) {
// base case
if (root === null) return -1;
// if current node is the target, find the
// depth of root, compare it with ans and
// return 1.
if (root.key === target) {
let depth = findDepth(root) - 1;
ans[0] = Math.max(ans[0], depth);
return 1;
}
let left = findTarNode(root.left, target, ans);
// If target node is found in the left subtree
// ,then compare the depth of right subtree and dis
// of target node with ans.
if (left !== -1) {
let depth = findDepth(root.right);
ans[0] = Math.max(ans[0], left + depth);
return left + 1;
}
// If target node is found in the right subtree
// ,then compare the depth of left subtree and dis
// of target node with ans.
let right = findTarNode(root.right, target, ans);
if (right !== -1) {
let depth = findDepth(root.left);
ans[0] = Math.max(ans[0], right + depth);
return right + 1;
}
// if target node is not found,
// return -1.
return -1;
}
function minTime(root, target) {
let ans = [0];
findTarNode(root, target, ans);
return ans[0];
}
// Driver Code
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
// Target
let target = 2;
console.log(minTime(root, target));
Burning Tree | DSA Problem