Skip to content

Commit 4af1622

Browse files
committed
problem: 0863 all nodes distance k in binary tree
1 parent 6a7fa92 commit 4af1622

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# 0863. All Nodes Distance K in Binary Tree
2+
3+
* Difficulty: medium
4+
* Link: https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/
5+
* Topics: DFS-BFS
6+
7+
# Clarification
8+
9+
1. Check the inputs and outputs
10+
- INPUT: TreeNode, TreeNode, k
11+
- OUTPUT: List[int]
12+
13+
# Naive Solution
14+
15+
### Thought Process
16+
17+
1. transfer the tree to graph
18+
2. start from the target node from the graph using bfs
19+
3. return the level k
20+
- Implement
21+
22+
```python
23+
# Definition for a binary tree node.
24+
# class TreeNode:
25+
# def __init__(self, x):
26+
# self.val = x
27+
# self.left = None
28+
# self.right = None
29+
30+
class Solution:
31+
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
32+
33+
if not root:
34+
return []
35+
36+
#1. transfer the tree to graph
37+
graph = {}
38+
q = collections.deque()
39+
q.append(root)
40+
41+
while q:
42+
current = q.popleft()
43+
if not graph.get(current.val):
44+
graph[current.val] = []
45+
if current.left:
46+
leftVal = current.left.val
47+
graph[current.val].append(leftVal)
48+
graph[leftVal] = [current.val]
49+
q.append(current.left)
50+
if current.right:
51+
rightVal = current.right.val
52+
graph[current.val].append(rightVal)
53+
graph[rightVal] = [current.val]
54+
q.append(current.right)
55+
#2. start from the target node from the graph using bfs
56+
q.append(target.val)
57+
level = 0
58+
result = []
59+
while level <= k:
60+
if not q:
61+
return []
62+
lenq = len(q)
63+
result = []
64+
for i in range(lenq):
65+
current = q.popleft()
66+
result.append(current)
67+
for n in graph.get(current):
68+
graph[n].remove(current)
69+
q.append(n)
70+
level += 1
71+
#3. return the level k
72+
return result
73+
```
74+
75+
76+
### Complexity
77+
78+
- Time complexity:O(N)
79+
- Space complexity:O(N)

0 commit comments

Comments
 (0)