-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhelper.py
112 lines (95 loc) · 2.55 KB
/
helper.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
from typing import List, Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def create_link(nums: List[int]) -> Optional[ListNode]:
if len(nums) == 0:
return None
head = ListNode(nums[0])
cur = head
for num in nums[1:]:
node = ListNode(num)
cur.next = node
cur = node
return head
def trave_link(head: Optional[ListNode]) -> List[int]:
nums = []
if head is None:
return nums
# [h] -> [] -> None
while head:
nums.append(head.val)
head = head.next
return nums
def create_ring_link(nums: List[int], pos) -> Optional[ListNode]:
"""创建链表"""
if len(nums) == 0:
return None
head = ListNode(nums[0])
cur = head
for num in nums[1:]:
node = ListNode(num)
cur.next = node
cur = node
# 无环
if pos == -1:
return head
# 有环,找到交点,尾结点指向它
node = head
while pos > 0 and node:
node = node.next
pos -= 1
cur.next = node
return head
def trave_ring_link(head: Optional[ListNode]) -> List[int]:
"""遍历链表"""
nums = []
if head is None:
return nums
count = 10
while head and count:
nums.append(head.val)
head = head.next
count -= 1
return nums
class TreeNode:
def __init__(self, val):
self.val = val
self.left: Optional[TreeNode] = None
self.right: Optional[TreeNode] = None
def create_binary_tree(nums: List[Optional[int]], index: int) -> Optional[TreeNode]:
"""
1
2 2
3 4 4 3
左右结点分别为 2*i+1, 2*i+2
"""
# 递归创建二叉树
if index >= len(nums) or nums[index] is None:
return
root = TreeNode(nums[index])
root.left = create_binary_tree(nums, index * 2 + 1)
root.right = create_binary_tree(nums, index * 2 + 2)
return root
def bfs_binary_tree(root: Optional[TreeNode]) -> List[int]:
# 层序遍历
if root is None:
return []
queue = [root]
results = []
while queue:
size = len(queue)
nums = []
next_queue = []
for index in range(size):
node = queue[index]
nums.append(node.val if node else None)
if node:
next_queue.append(node.left)
next_queue.append(node.right)
if any(num is not None for num in nums):
results.extend(nums)
queue = next_queue
return results