-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlist_of_depth_LCCI.py
More file actions
47 lines (41 loc) · 1.2 KB
/
list_of_depth_LCCI.py
File metadata and controls
47 lines (41 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Definition for a binary tree node.
from collections import deque
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def listOfDepth(self, tree: TreeNode) -> List[ListNode]:
res = []
pre_depth = 0
cur_head = ListNode(0)
p = cur_head
q = deque([(tree, 0)])
while q:
item = q.popleft()
node = item[0]
depth = item[1]
if pre_depth == depth:
p.next = ListNode(node.val)
p = p.next
else:
res.append(cur_head.next)
cur_head = ListNode(0)
p = cur_head
p.next = ListNode(node.val)
p = p.next
pre_depth = depth
if node.left:
q.append((node.left, depth + 1))
if node.right:
q.append((node.right, depth + 1))
# 记得把最后一链表加上
res.append(cur_head.next)
return res