Burn the Binary tree from the Target nodeWhat is a Binary tree?The binary tree is a type of generic tree where one node can have a maximum of two child nodes. We are given a binary tree and target node. We have to burn the binary tree starting from the target node and print the nodes burnt at each level. Burning means at time = 0 target node will burn, and then the parent and its child node will be burnt. For example: At level 0: The burning node is 5. At level 1: The burning nodes are 2 and 7. At level 2: The burning nodes are 1, 4 and 9. At level 3: The burning node is 3. At level 4: The burning node is 6. At level 5: The burning node is 8. Method 1In this approach, our first task will be to get the target node. So recursively, we will search for the target node. After finding the target node, we will print the node and then we will add its left and right children into the queue. For each node, we will call the recursive function for its left and right subtree. If the recursive function returns one, which means in that subtree, we found the target node, so we will print the elements present in the queue and then we will print the current node. In the main function after this recursive call, we will check if there are some nodes remaining or not by checking the queue size. We will print the elements present in the queue. Java code: Output: Time complexity: O(N), where N is the number of nodes. Space complexity: O(N) for queue. Method 2The second approach is to convert the given binary tree into an undirected graph. Then after converting the tree into a graph, we will use the BFS approach to burn the nodes. For each node, we have its children and the parent so we will convert the parents and children as the neighbor nodes for any particular node. We will use the queue data structure to get the Breadth First search of the given graph. We will use a hashmap of nodes vs ArrayList of nodes which will contain the list of neighbors of each node we can access in constant time. Java code: Output: Time complexity: O(N), where N is the number of nodes. Space complexity: O(N) Note: This method has a limitation. This method is changing the given data structure, so there are high chances of data loss and data complexity at a higher level, so this method should not be preferred. |