×

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

Queue Data Structure

Queue in DS: The queue is a non-primitive and linear data structure. It works on the principle of FIFO (First In First Out). That is, the element that is added...

4 minutes read.

Cocktail Sort

C Program executes cocktail sort. Combo sort is a somewhat straightforward arranging calculation initially planned by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered by Stephen Lacey and Richard Box...

5 minutes read.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

Strings in Data Structures

Strings and functions in C A string is a collection of characters. We'll learn how to declare strings, operate with strings in C programming, and use pre-defined string handling routines. We'll look...

7 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.

Bin Packing Problem (How to minimize the number of used Bins)

You have been given an array. The values of the array represent the size of n different items. You have been also given some bins. You have to store the...

3 minutes read.

Insertion Sort in Data Structures

Insertion Sort in C++ Insertion sort is a sorting algorithm that, in each iteration, installs an unsorted element in its proper position Insertion sort operates in a similar way to how we...

3 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

Bitwise Operators and their Important Tricks

In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task,...

5 minutes read.

Merge Conflicts and ways to handle them

Merge Conflicts Whenever dealing with the Git merge operations, conflicts will be the frequently occurred. When more than two developers work on the same file on different systems using Git, they...

4 minutes read.

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

Write Main Difference Between Tree and Graph in Data Structures

Graph: The graph has two sets, which are considered V and E. These vertices are also called nodes, and edges are referred to as arcs connecting any two nodes in a...

4 minutes read.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

3 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

4 minutes read.

Dynamic memory allocation of structure in C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

5 minutes read.

Understanding Data Processing

Introduction Data In our everyday lives, any task that we perform online is related to data. Millions of pieces of data are produced every second across the globe. Data production is largely...

4 minutes read.