Burn the binary tree starting from the target nodeTaking into account a binary tree and a target node. The fire starts to spread throughout the entire tree when it is supplied to the target node. The goal at hand is to print the burning node sequence of the binary tree. Guidelines for burning the nodes:
ExampleInput : Output: 14 21, 24, 10 15, 12 22, 23, 13 Explanation: Node 14 burns first, then nodes 21, 24, 10, and so on catch fire from it. Until the tree completely burns, this process is repeated. Approach 1First, in a binary tree, perform a recursive search on the target node. Once the target node has been located, print it and place its left and right children (if any) in a queue. then come back. Obtain the queue's size now, and execute the while loop. Print the queued components. Below is the implementation of the approach Output: Time Complexity: O(n), Since there are n nodes in the binary tree, the temporal complexity of the suggested method is O(n). Because each node is only accessed once in the worst scenario, this is the case. Every node, which has n nodes in total, is processed once by the while loop of the burn_tree_util function. Space Complexity: Even in the worst scenario, the space complexity is O(n). For the worst-case scenario, the queue (q), where n is the number of nodes at the last level of the binary tree, can only store n/2 nodes. The final level of a complete binary tree has about n/2 nodes. Consequently, the queue causes the space complexity to be O(n). Approach 2Transform the tree into an undirected graph, then display the level order traversal of that graph.
#Python program for the above approach Output: Time Complexity: O(n) is the time complexity, where n is the binary tree's node count. To construct the map and carry out BFS traversal, we must traverse every node in the binary tree. Space Complexity: O(n) is the space complexity, where n is the binary tree's node count. All of the nodes in the unordered map and the queue that is utilized for BFS traversal must be stored. Approach 3The aim is to traverse the tree in reverse order and return a measure of the current node's distance from the target node. To do this, we examine whether the target was located during each recursive iteration. Follow the steps below to implement the above idea:
Below is the implementation of the code Output: Time Complexity: O(n), Because the mentioned code only conducts a single tree traverse, its time complexity is O(n). Updating the unordered_map and making the recursive calls require constant time at each node. As a result, the temporal complexity of the tree is linear in the number of nodes. Space Complexity: O(n), where n is the number of nodes in the tree, is the Auxiliary Space for the code shown above. This is a result of the code using an unordered_map, whose size grows linearly with the number of nodes in the tree, to store the nodes burned at each stage. |