Description
Given a binary tree, a target node, and an integer k, return a list of all nodes that are exactly distance k from the target node.
Examples
root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2[7,4,1]Nodes at distance 2 from node 5.
root = [1,2,3,4,5,null,6,null,null,null,null,null,7], target = 2, k = 3[7]Starting from target node 2, nodes at distance 3 are found by traversing both up and down the tree. Going up from 2→1→3→6 reaches node 6 at distance 3, and 6→7 is distance 4. The only node at exactly distance 3 from node 2 is 7 (via path 2→1→3→6→7 counting edges).
root = [10,20,30], target = 10, k = 1[20,30]This is a simple case with a small tree. Starting from the root node 10 (target), looking for all nodes at distance 1. The direct children of node 10 are nodes 20 and 30, both at distance 1 from the target. Since k=1, only need to go one step away from the target node, which gives us both left child (20) and right child (30).
Constraints
- •
1 ≤ number of nodes ≤ 500 - •
0 ≤ k ≤ 1000