10. Nodes at Given Distance in Binary Tree
Problem Statement
The problem can be found at the following link: Question Link
My Approach
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 distancek
as parameters. This function is used to trace nodes at distancek
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 theout
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 andk
as parameters to find nodes at distancek
.Return
k - 1
to indicate that the target node has been found at distancek
.
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 distancek
.Sort the
out
vector in ascending order.Return the sorted
out
vector as the result."
Time and Space Complexity
Time Complexity: The time complexity of this solution is
O(N)
, whereN
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 distancek
. For sorting theout
vector, we use thesort
function, which has a time complexity ofO(NlogN)
.Auxiliary Space Complexity: The auxiliary space complexity is
O(H)
, whereH
is the height of the binary tree. This space is used for the recursive call stack during the DFS traversal.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 getlost01/gfg-potd repository.
Last updated