All Nodes at Distance K Python SolutionIn this tutorial, we will solve a problem on Binary Tree data structure. The problem statement is that if we are provided with the root node of the binary tree, the target node, and the distance value k, we need to return the list of all the values present at distance k from the target node in the given binary tree. Consider the tree:Look at the tree diagram above Input: target = Node object with value 2. root = Node object pointing to 1. k = 2. Output: [8, 9, 3] If the target node is 4 and k is equal to 4, then the output will be [6, 7] Approach - 1The main trick in this question is that we have to do more than traverse from top to bottom. We need two kinds of pointers. These are:
The first pointer is the regular pointer present in the structure of the binary tree. However, the second kind of pointer is not available to us. Hence, we need to create this pointer. Once we get both pointers, we must traverse the nodes starting from the target nodes. We will traverse in the radially outward direction from the target node, and on the completion of each traversal, we will decrement k by 1. But the main question is how to get the nodes attached to the parent node of the target node. We have to traverse through the nodes that are not a part of the subtrees of the target node. For every node present in the upper tree, we will find the distance of that node from the target node, let this distance be dist, and now we will traverse through the other subtree of the nodes present in the upper tree and store all the nodes present at k - dist distance from the ancestor node. Below is the code of the above approach: Code Output: 4 1 2 Time Complexity: This algorithm has the worst-case time complexity of O(N). The time complexity is not more than linear because no node in this algorithm is traversed more than once. Space Complexity: This program has O(h) space complexity. Here h is the height of the given binary tree. Approach - 2This approach is more straightforward than the previous approach.
Code Output: [4, 1] Time complexity: O(n) |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India