Python solution beats 86.75% for Leetcode 863: All Nodes Distance K in Binary Tree
I believe that solving leetcode problems for fun could help you keep your brain active 😄
You can find original problem HERE on Leetcode
📑Description:
We are given a binary tree (with root node root
), a target
node, and an integer value K
.
Return a list of the values of all nodes that have a distance K
from the target
node. The answer can be returned in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2Output: [7,4,1]Explanation:
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.

Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.
Note:
- The given tree is non-empty.
- Each node in the tree has unique values
0 <= node.val <= 500
. - The
target
node is a node in the tree. 0 <= K <= 1000
.
📝My O(n) Solution:
Noticd: You can also create the dictionary manually through the raw python dictionary, but using python “collections” library saves both coding and machine time.
📖Explain:
Function “router” saves all nodes that directly connect with the current nodes in the dictionary. (“Directly connect” means that one node connects with another one without any other nodes between these two nodes.)
For the input tree in example 1, if you put a breakpoint after generating the dictionary, you can see the dictionary object looks like that:

Function “neighbors” search nodes that connect with the current node, once visited, put it in ‘seem’ set( You should use a set instead of a list because it is faster to find an element in a hash table than a list)and will not visit it anymore in the following loops. Do it for K times, put nodes visited in the final loop in list “ans”
Result after submitting to Leetcode server:
Accepted
- 57/57 cases passed (32 ms)
- Your runtime beats 86.75 % of python3 submissions
- Your memory usage beats 62.5 % of python3 submissions (14.1 MB)