Back to course home
0% completed
Vote For New Content
All Nodes Distance K in Binary Tree (medium)
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
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Like the course? Get enrolled and start learning!
On this page
Problem Statement
Examples
Try it yourself