生成二叉树
# 节点类
class Node(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 树生成代码
def generate_tree(vals):
if len(vals) == 0:
return None
que = [] # 定义队列
fill_left = True # 由于无法通过是否为 None 来判断该节点的左儿子是否可以填充,用一个记号判断是否需要填充左节点
for val in vals:
node = Node(val) if val else None # 非空值返回节点类,否则返回 None
if len(que)==0:
root = node # 队列为空的话,用 root 记录根结点,用来返回
que.append(node)
elif fill_left:
que[0].left = node
fill_left = False # 填充过左儿子后,改变记号状态
if node: # 非 None 值才进入队列
que.append(node)
else:
que[0].right = node
if node:
que.append(node)
que.pop(0) # 填充完右儿子,弹出节点
fill_left = True #
return root
# 定义一个dfs打印中序遍历
def dfs(node):
if node is not None:
dfs(node.left)
print(node.val, end=' ')
dfs(node.right)
# 定义一个bfs打印层序遍历
def bfs(node):
que = []
que.append(node)
while que:
l = len(que)
for _ in range(l):
tmp = que.pop(0)
print(tmp.val, end=' ')
if tmp.left:
que.append(tmp.left)
if tmp.right:
que.append(tmp.right)
print('|', end=' ')
# test
null = None
vals = [3,9,20,null,null,15,7]
tree = generate_tree(vals)
print('中序遍历:')
dfs(tree) # 9 3 15 20 7
print('\n层序遍历:')
bfs(tree) # 3 | 9 20 | 15 7 |
生成列表
#定义节点
class ListNode():
def __init__(self, x):
self.val = x
self.next = None
#将传入的数组转化为链表
def create_linked_list(arr):
head = ListNode(arr[0])
cur = head
for i in range(1, len(arr)):
cur.next = ListNode(arr[i])
cur = cur.next
return head
#传入链表头节点,以数组形式返回
def print_linked_list(head):
cur = head
res = []
while cur:
res.append(cur.val)
cur = cur.next
return res
class Solution():
def mergeTwoLists(self, l1, l2):
pre = ListNode(0)
head = pre
while l1 and l2:
if l1.val >= l2.val:
pre.next = l2
l2 = l2.next
else:
pre.next = l1
l1 = l1.next
pre = pre.next
pre.next = l1 if l1 else l2
return head.next
if __name__ == "__main__":
head1 = create_linked_list([1, 2, 4])
head2 = create_linked_list([1, 3, 4])
solution = Solution()
sorted_lists = solution.mergeTwoLists(head1, head2)
print(print_linked_list(sorted_lists))
#输出:[1, 1, 2, 3, 4, 4]
注:放到本地可以直接跑哦~
猜你喜欢:👇🏻
⭐【Leetcode】创建链表
⭐【Leetcode】创建二叉树
⭐【Leetcode】大神总结的链表常见面试问题