[Naive Approach] Using Recursive Traversal (DFS) - O(n) time and O(h) Space
The idea is to use a recursive approach to find all nodes at a specified distance k from the root of a binary tree. or nodes at greater distances, the function recursively explores both left and right children, decrementing k with each call. And add the current node's data when k becomes 0.
Algorithm:
If root is NULL or k < 0, return
If k == 0, add current nodeβs value to result
Recur for left subtree with k - 1
Recur for right subtree with k - 1
Output
Nodes at distance 2: 2 9 13
Time Complexity: O(n) where n is number of nodes in the given binary tree. Space Complexity : O(h) where h is the height of binary tree.
[Better Approach] Using Queue - O(n) time and O(n) Space
This idea is based on line by line level order traversal. Start with an empty queue, enqueue the root, and set the level to 0. While the queue isn't empty, if the level equals k, store and return node values. For each node, dequeue it and enqueue its children. Increment the level after processing all nodes. return an empty list if no nodes are at distance k.
Algorithm:
Push root into the queue and set level or lvl = 0, then start level order traversal.
At each step, get current level size and check if lvl == k; if yes, store all node values and return.
Otherwise, remove each node and push its left and right children into the queue.
After processing the level, increment lvl and continue.
If the queue becomes empty before reaching k, return the empty result.
Output
Nodes at distance 2: 2 9 13
Time Complexity: O(n) where n is number of nodes in the given binary tree. Space Complexity: O(n)
[Expected Approach] Using Stack - O(n) time and O(n) Space