×

Burning binary tree

Burn the Binary tree starting from the target node

You have given a binary tree and a target node value. Now you have to burn the tree from target node. You have to print the sequence in which the tree will burn.

There are some conditions:

  1. A node will burn only once.
  2. Every node takes same time for burning.
  3. Fire will spread through adjacent nodes only

Input-

Burn the Binary tree starting from the target node

Target node = 4

Output-       

4
2      3       5
0      6
8
7      9

Explanation- First, the node with value 4 will burn so, it is printed first. After that 2, 3, 5 nodes will catch fire at same time so, they printed in same line. In this way, full tree is burnt.

Concept behind the solution

First, we find the target node by recursion then we store right and left child using a queue. After that we will use this queue to print the burning tree.

Code -

// CPP program to print the nodes of burning tree

Program in C++

#include <bits/stdc++.h>
using namespace std;
struct Node {
	int key;
	struct Node *left, *right;
};
Node* newNode(int key)
{
	Node* temp = new Node;
	temp->key = key;
	temp->left = temp->right = NULL;
	return (temp);
}
int burnTreeUtil(Node* root, int target, queue<Node*>& q)
{
	if (root == NULL) {
		return 0;
	}
	if (root->key == target) {
		cout << root->key << endl;
		if (root->left != NULL) {
			q.push(root->left);
		}
		if (root->right != NULL) {


			q.push(root->right);
		}
		return 1;
	}


	int a = burnTreeUtil(root->left, target, q);


	if (a == 1) {
		int qsize = q.size();
		while (qsize--) {
			Node* temp = q.front();
			cout << temp->key << " , ";
			q.pop();
			if (temp->left != NULL)
				q.push(temp->left);
			if (temp->right != NULL)
				q.push(temp->right);
		}


		if (root->right != NULL)
			q.push(root->right);


		cout << root->key << endl;
		return 1;
	}


	int b = burnTreeUtil(root->right, target, q);


	if (b == 1) {
		int qsize = q.size();
		


		while (qsize--) {
			Node* temp = q.front();
			cout << temp->key << " , ";
			q.pop();
			if (temp->left != NULL)
				q.push(temp->left);
			if (temp->right != NULL)
				q.push(temp->right);
		}


		if (root->left != NULL)
			q.push(root->left);


		cout << root->key << endl;
		return 1;
	}
}
void burnTree(Node* root, int target)
{
	queue<Node*> q;
	burnTreeUtil(root, target, q);
	while (!q.empty()) {
		int qSize = q.size();
		while (qSize > 0) {
			Node* temp = q.front();
			cout << temp->key;
			if (temp->left != NULL) {
				q.push(temp->left);
			}
			if (temp->right != NULL) {
				q.push(temp->right);
			}


			if (q.size() != 1)
				cout << " , ";


			q.pop();
			qSize--;
		}
		cout << endl;
	}
}
int main()
{
	Node* root = newNode(10);
	root->left = newNode(12);
	root->right = newNode(13);


	root->right->left = newNode(14);
	root->right->right = newNode(15);


	root->right->left->left = newNode(21);
	root->right->left->right = newNode(22);
	root->right->right->left = newNode(23);
	root->right->right->right = newNode(24);
	int targetNode = 14;
	burnTree(root, targetNode);


	return 0;
}

// JAVA program to print the nodes of burning tree

Program in Java

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


class TreeNode
{
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode() {}
	TreeNode(int val) { this.val = val; }
	TreeNode(int val, TreeNode left, TreeNode right)
	{
		this.val = val;
		this.left = left;
		this.right = right;
	}
}


class Solution {
	public static int search(TreeNode root,
							int num,
							Map<Integer,
							Set<Integer> > lm)
	{
		if (root != null)
		{
			if (root.val == num)
			{


				levelOrderStoredInMap(root.left, 1,
									lm);
				levelOrderStoredInMap(root.right, 1,
									lm);
				
				return 1;
			}
			int k = search(root.left, num, lm);
			if (k > 0)
			{
				storeRootAtK(root, k, lm);
							levelOrderStoredInMap(root.right, k + 1,
									lm);
				return k + 1;
			}
			k = search(root.right, num, lm);
			if (k > 0)
			{
				storeRootAtK(root, k, lm);
				levelOrderStoredInMap(root.left, k + 1,
									lm);
				return k + 1;
			}
		}
		return -1; 
	}


	public static void levelOrderStoredInMap(
		TreeNode root, int k,
		Map<Integer, Set<Integer> > lm)
	{
		if (root != null) {
			storeRootAtK(root, k, lm);
			levelOrderStoredInMap(root.left, k + 1,
								lm);
			levelOrderStoredInMap(root.right, k + 1,
								lm);
		}
	}


	private static void
	storeRootAtK(TreeNode root, int k,
				Map<Integer, Set<Integer> > lm)
	{
		if (lm.containsKey(k)) {
			lm.get(k).add(root.val);
		}
		else {
			Set<Integer> set = new HashSet<>();
			set.add(root.val);
			lm.put(k, set);
		}
	}
	public static void main(String[] args)
	{	
		TreeNode root = new TreeNode(12);
		root.left = new TreeNode(13);
		root.right = new TreeNode(10);
		root.right.left = new TreeNode(14);
		root.right.right = new TreeNode(15);
		TreeNode left = root.right.left;
		TreeNode right = root.right.right;
		left.left = new TreeNode(21);
		left.right = new TreeNode(24);
		right.left = new TreeNode(22);
		right.right = new TreeNode(23);
		Map<Integer, Set<Integer> > lm
			= new HashMap<>();
		search(root, 14, lm);
		System.out.println(14);
		for (Integer level : lm.keySet())
		{
			for (Integer val : lm.get(level))
			{
				System.out.print(val + " ");
			}
			System.out.println();
		}
	}
}

Output-

14
21 , 22 , 13
15 , 10
23 , 24 , 12

Related Topics

Merge Sort

Merge Sort is one of the most widely used sorting algorithms, and it is based on the Divide and Conquer principle. A problem is subdivided into multiple sub-problems in this method....

8 minutes read.

Binary Tree in Data Structures

What is a Binary Tree in Data Structures? The term binary itself means bi, which implies two of anything. So very clearly, we know we present the trees in the form...

6 minutes read.

Serialize and Deserialize a Binary Tree

Implementation // Writing a C++ program to check the serialization and deserialization of binary tree.   #include <iosstream> /* A binary tree node contains a key and a pointer to the left and right...

4 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Complete Binary tree

In this article, we will discuss the complete binary tree. But before start discussing the complete binary tree, we should first see a brief description of a binary tree. What is...

7 minutes read.

Stack vs Heap Memory Allocation Data Structure

Difference Between Stack and Heap Memory Allocation Stack Memory Stack memory allocation is a way to use the system memory as a temporary storage of the data which is act like last-in-first-out...

3 minutes read.

Convert Sorted List to Binary Search Tree

Implementation // creating the C++ implementation of the following approach: - #include <bits/stdc++.h> using namespace std; /* Create the link list node and see its implementation. */ class L__Nod { public: int record; L__Nod* next; }; /* constructing a new binary...

15 minutes read.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

3 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

Identical Linked Lists

Identical Linked Lists In this problem, we have given two linked lists, and we need to check whether the given linked lists are identical or not. Identical means they have the...

4 minutes read.

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Sort the linked list of 0s, 1s and 2s

Sort the linked list of 0s, 1s and 2s In this, we are given a linked list of 0s, 1s, and 2s, and we need to sort it. Examples: Input: 1  ->  1 ...

2 minutes read.

Difference between Structured and Object-Oriented Analysis

Analysis means observing and collecting relevant information about the structure of something or the basic details of a system's requirements. Structured and Object Oriented Analysis are both widely used in...

2 minutes read.

What is B tree?

What do you mean by B Tree in Data Structures? In the technological world, a B tree is simply a well-managed and coordinated tree and an integral part of the data...

6 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

What Is Dfs Algorithm in Data Structures

DFS stands for Depth First Search. Generally, it is a repetitive or decidable type of algorithm which is basically used in identifying all the vertices or nodes of a graph...

5 minutes read.

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.

Tree in Data Structure

Tree A tree is a non-linear data structure by which hierarchical data is displayed. As we know that there are many trees in the forest, similarly the data structure also contains...

3 minutes read.

Tree terminology in Data structures

Data structures The storage used to organize and store data is known as a data structure, and it is a method where data can be arranged on a computer to be...

6 minutes read.