10. Nodes at Given Distance in Binary Tree
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
The intuition for solving this problem involves using depth-first search (DFS) to first find the target node and then tracing the Kth distance from the target. Since it is a binary tree, we employ backtracking to find the Kth distance from the parent's side link.
Here is what I have done:
To achieve this, I followed these steps:
Created a function trace
that takes the current node and the remaining distance k
as parameters. This function is used to trace nodes at distance k
from the current node.
In the trace
function:
If k
is less than 0 or the current node is null, return.
If k
is 0, add the current node's data to the out
vector and return.
In the findDist
function:
If the current node is null, return INT_MIN
to indicate that the target node was not found.
If the current node's data matches the target node's data:
Call the trace
function with the current node and k
as parameters to find nodes at distance k
.
Return k - 1
to indicate that the target node has been found at distance k
.
Recursively search for the target node in the left and right subtrees:
If found in the left subtree, process accordingly and return the updated distance.
If found in the right subtree, process accordingly and return the updated distance.
In the KDistanceNodes
function:
Initialize an empty vector out
to store the result.
Call the findDist
function to find the target node and trace nodes at distance k
.
Sort the out
vector in ascending order.
Return the sorted out
vector as the result."
Time Complexity: The time complexity of this solution is O(N)
, where N
is the number of nodes in the binary tree. This is because we perform a single DFS traversal of the tree to find the target node and trace nodes at distance k
. For sorting the out
vector, we use the sort
function, which has a time complexity of O(NlogN)
.
Auxiliary Space Complexity: The auxiliary space complexity is O(H)
, where H
is the height of the binary tree. This space is used for the recursive call stack during the DFS traversal.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.