Python DFS and BFS
Explanation\nA recursive dfs funciton connect help to build up a map conn.\nThe key of map is node\'s val and the value of map is node\'s connected nodes\' vals
## **Explanation**\nA recursive dfs funciton `connect` help to build up a map `conn`.\nThe key of map is node\'s val and the value of map is node\'s connected nodes\' vals.\nThen we do N times bfs search loop to find all nodes of distance `K`\n<br>\n\n**Python**\ncommented by @0alexzhong0\n```py\ndef distanceK(self, root, target, K):\n    conn = collections.defaultdict(list)\n    def connect(parent, child):\n        # both parent and child are not empty\n        if parent and child:\n            # building an undirected graph representation, assign the\n            # child value for the parent as the key and vice versa\n            conn[parent.val].append(child.val)\n            conn[child.val].append(parent.val)\n        # in-order traversal\n        if child.left: connect(child, child.left)\n        if child.right: connect(child, child.right)\n    # the initial parent node of the root is None\n    connect(None, root)\n    # start the breadth-first search from the target, hence the starting level is 0\n    bfs = [target.val]\n    seen = set(bfs)\n    # all nodes at (k-1)th level must also be K steps away from the target node\n    for i in range(K):\n        # expand the list comprehension to strip away the complexity\n        new_level = []\n        for q_node_val in bfs:\n            for connected_node_val in conn[q_node_val]:\n                if connected_node_val not in seen:\n                    new_level.append(connected_node_val)\n        bfs = new_level\n        # add all the values in bfs into seen\n        seen |= set(bfs)\n    return bfs\n```
[]