"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
lists=[]
if not root:
return lists
queue=deque([root])
while queue:
size=len(queue)
list=[]
for i in range(size):
node=queue.popleft()
list.append(node.val)
if node.children:
queue.extend(node.children)
lists.append(list)
return lists
这里有个问题,根据以往的经验,我写完代码后报list没有val属性,
实际原因为:这里面的Node节点跟以往的不一样,以往的是有值有左孩子有孩子,
本题的Node节点有val和children属性,children是列表
from collections import deque
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
lists=[]
if not root:
return lists
queue=deque([root])
while queue:
size=len(queue)
list=[]
for _ in range(size):
node=queue.popleft()
list.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
maxnum=max(list)
lists.append(maxnum)
return lists
116.填充每个节点的下一个右侧节点指针
**本题没有用队列解,用的list解的,这不大明白,各个二叉树具体是什么基础数据类型;
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
if not root:
return None
list=[root] #这里怎么判断这个树是一个list型的
while list:
n=len(list)
for i in range(n):
node = list.pop(0)
if node.left:
list.append(node.left)
if node.right:
list.append(node.right)
if i == n-1:
break
node.next=list[0]
return root
#跟着答案敲的
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None
queue=[root]
while queue:
n=len(queue)
tail=None #
for i in range(n):
cur=queue.pop(0)
if tail:
tail.next=cur
tail=cur
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return root
104
给定一个二叉树,找出其最大深度。
跟着敲的,不明白 queue=[root]这个 这种写法是用列表实现的队列
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
queue=[root]
depth=0
while queue:
n=len(queue)
for i in range(n):
node=queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
depth +=1
return depth
[二叉树的最小深度](https://leetcode.cn/problems/minimum-depth-of-binary-tree/)
111. 二叉树的最小深度
跟着敲的
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root==None:
return 0
queue=[(root,1)]
while queue:
cur,depth=queue.pop(0)
if cur.left==None and cur.right==None:
return depth
if cur.left:
queue.append((cur.left,depth+1))
if cur.right:
queue.append((cur.right, depth + 1))
return 0