0% completed
Problem Statement
Given the root
of a binary tree, a target
node, and a distance k
, find all the nodes in the tree that are exactly k
edges away from the target
node. You may return these nodes' values in any order.
Examples
Example 1
- Input: root =
[1, 2, 3, 4, 5, null, 6, 7, 8]
, target =3
, k =1
- Expected Output:
[6, 1]
- Justification: Nodes
1
and6
are one edge away from node3
.
Example 2
- Input: root =
[1, 2, 3, null, 4, 5, 6]
, tarrget =2
, k =2
- Expected Output:
[3]
- Justification: Node
3
is two edges away from node2
.
Example 3
- Input: root =
[1, 2, 3, 4, 5, null, null, null, null, 6, 7]
, target =4
, k =3
- Expected Output:
[6, 7, 3]
- Justification: Nodes
6
,7
and3
are three edges away from node4
.
Constraints:
- The number of nodes in the tree is in the range [1, 500].
- 0 <= Node.val <= 500
- All the values Node.val are unique.
- target is the value of one of the nodes in the tree.
- 0 <= k <= 1000
Solution
To solve this problem, we need to traverse the binary tree and find all nodes that are k
edges away from a given target node. We can achieve this by using a two-step approach. First, we need to convert the tree into a graph structure so that we can easily navigate through the nodes, regardless of their direction (parent or child). This graph will allow us to perform a breadth-first search (BFS) starting from the target node to find all nodes that are exactly k
edges away. The BFS approach ensures that we efficiently explore all possible paths to the nodes at the desired distance, making it an effective solution for this problem.
Step-by-Step Algorithm
-
Initialize Data Structures:
- Create a dictionary
parentMap
to store the parent of each node. - Create a list
result
to store the nodes at distancek
.
- Create a dictionary
-
Build Parent Map:
- Define a helper method
buildParentMap
that takes a node and its parent as arguments. - For each node, store its parent in
parentMap
. - Recursively call
buildParentMap
for the left and right children of the current node.
- Define a helper method
-
Breadth-First Search (BFS):
- Initialize a queue
queue
and add the target node to it. - Initialize a set
seen
and add the target node to it to track visited nodes. - Initialize a variable
distance
to zero.
- Initialize a queue
-
Perform BFS:
- While the queue is not empty:
- If
distance
equalsk
, collect all nodes in the queue intoresult
and returnresult
. - For each node in the current level:
- Dequeue the node.
- For each neighbor (left child, right child, parent):
- If the neighbor exists and is not in
seen
, add it toseen
and enqueue it.
- If the neighbor exists and is not in
- Increment
distance
by one after processing all nodes at the current distance.
- If
- While the queue is not empty:
-
Return Result:
- If no nodes are found at distance
k
, return an empty list.
- If no nodes are found at distance
Algorithm Walkthrough
Build the Parent Map in DFS Manner
We use a DFS traversal to build the parent map, starting from the root node. Each step includes setting the parent of a node, then recursively moving to the left and right children.
-
Start DFS with Root Node (
1
):- Set the parent of Node
1
tonull
(no parent for root). - Recur on the left child (Node
2
).
- Set the parent of Node
-
Node
2
:-
Set the parent of Node
2
to Node1
. -
Recur on the left child (Node
4
). -
Node
4
:- Set the parent of Node
4
to Node2
. - Node
4
has no children, so backtrack to Node2
.
- Set the parent of Node
-
Back to Node
2
:- Now recur on the right child (Node
5
).
- Now recur on the right child (Node
-
Node
5
:-
Set the parent of Node
5
to Node2
. -
Recur on the left child (Node
6
). -
Node
6
:- Set the parent of Node
6
to Node5
. - Node
6
has no children, so backtrack to Node5
.
- Set the parent of Node
-
Back to Node
5
:- Now recur on the right child (Node
7
).
- Now recur on the right child (Node
-
Node
7
:- Set the parent of Node
7
to Node5
. - Node
7
has no children, so backtrack.
- Set the parent of Node
-
-
Backtrack fully to Node
1
.
-
-
Back to Root Node (
1
):- Now recur on the right child (Node
3
).
- Now recur on the right child (Node
-
Node
3
:- Set the parent of Node
3
to Node1
. - Node
3
has no children, so DFS is complete.
- Set the parent of Node
- Final Parent Map:
After completing the DFS traversal, the
parentMap
is as follows:
{
1: null,
2: 1,
3: 1,
4: 2,
5: 2,
6: 5,
7: 5
}
Queue Operations with Set Updates (BFS Traversal)
Next, we will show the state of the queue
and seen
set at each BFS level. We start BFS from the target node (4
) and progress level-by-level until reaching the required distance K = 3
.
-
Level 0 (distance = 0):
- Queue:
[4]
- Set:
{4}
- Target node
4
has no children but has a parent (2
). Add2
to the queue andseen
. - Increment
distance
to1
.
- Queue:
-
Level 1 (distance = 1):
- Queue:
[2]
- Set:
{2, 4}
- Node
2
has:- Left child
4
(already inseen
). - Right child
5
. Add5
to the queue andseen
. - Parent
1
. Add1
to the queue andseen
.
- Left child
- Increment
distance
to2
.
- Queue:
-
Level 2 (distance = 2):
- Queue:
[5, 1]
- Set:
{1, 2, 4, 5}
- Process node
5
:- Left child
6
. Add6
to the queue andseen
. - Right child
7
. Add7
to the queue andseen
. - Parent
2
(already inseen
).
- Left child
- Process node
1
:- Left child
2
(already inseen
). - Right child
3
. Add3
to the queue andseen
.
- Left child
- Increment
distance
to3
.
- Queue:
-
Level 3 (Distance = K(3)):
- Queue:
[6, 7, 3]
- Set:
{1, 2, 3, 4, 5, 6, 7}
- Since we’ve reached
distance = K
, all nodes currently in the queue (6
,7
, and3
) are at distanceK = 3
from the target node4
. - Add nodes in the queue to the result list.
- Queue:
The BFS traversal ends here, and the result list [6, 7, 3]
is returned as the final output.
Complexity Analysis
Time Complexity
-
Building the Parent Map:
- We traverse the entire tree once to build the parent map.
- This takes O(N) time, where ( N ) is the number of nodes in the tree.
-
Breadth-First Search (BFS):
- In the worst case, we might visit all the nodes.
- This also takes O(N) time.
Combining both steps, the total time complexity is O(N).
Space Complexity
-
Parent Map:
- The parent map stores a reference for each node, resulting in O(N) space.
-
Queue and Seen Set:
- In the worst case, the queue and seen set can store all nodes, resulting in O(N) space.
Combining both, the total space complexity is O(N).
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible