![]() |
VOOZH | about |
Given a binary tree and target node. By giving the fire to the target node and fire starts to spread in a complete tree. The task is to print the sequence of the burning nodes of a binary tree.
Rules for burning the nodes :
Examples:
Input : 12 / \ 13 10 / \ 14 15 / \ / \ 21 24 22 23 target node = 14 Output : 14 21, 24, 10 15, 12 22, 23, 13 Explanation : First node 14 burns then it gives fire to it's neighbors(21, 24, 10) and so on. This process continues until the whole tree burns. Input : 12 / \ 19 82 / / \ 41 15 95 \ / / \ 2 21 7 16 target node = 41 Output : 41 2, 19 12 82 15, 95 21, 7, 16
Approach :
First search the target node in a binary tree recursively. After finding the target node print it and save its left child(if exist) and right child(if exist) in a queue. and return. Now, get the size of the queue and run while loop. Print elements in the queue.
Below is the implementation of the above approach :
14 21 , 22 , 13 15 , 10 23 , 24 , 12
Time complexity :- O(N^2)
Space complexity :- O(N)
Another Approach: Convert the tree into undirected graph and print its level order traversal
14 10 21 24 12 15 13 22 23
Time Complexity: O(n), where n is the number of nodes in the binary tree. We need to traverse all the nodes in the binary tree to build the map and perform BFS traversal.
Space Complexity: O(n), where n is the number of nodes in the binary tree. We need to store all the nodes in the unordered_map and the queue used in BFS traversal.
An approach using DFS:
The idea is to do an inorder traversal of the tree, and return some information of how far the current node is from the target node. For this, we check if we found the target in each recursive iteration.
Follow the steps below to implement the above idea:
Please refer to the code below for a detailed C++ solution.
Nodes burnt at stage 3 are 23 24 12 Nodes burnt at stage 2 are 15 10 Nodes burnt at stage 1 are 21 22 13 Nodes burnt at stage 0 are 14
The time complexity of the above code is O(n), because the code performs a single traversal of the tree. At each node, it takes constant time to update the unordered_map and perform the recursive calls. Therefore, the time complexity is linear in the number of nodes in the tree.
The Auxiliary Space of the above code is O(n), where n is the number of nodes in the tree. This is because the code uses an unordered_map to store the nodes burnt at each stage, and the size of the map increases linearly with the number of nodes in the tree.