Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
Input: root = [1], target = 1, k = 3
Output: []
First use DFS to construct a graph like dictionary and then use BFS to iterate K levels start from the target point.
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""classSolution:defconnect(self,root:'Node')->'Node':ifrootisNoneorroot.leftisNone:returnrootroot.left.next=root.rightifroot.next:root.right.next=root.next.leftself.connect(root.left)self.connect(root.right)returnroot