文章目录
二叉树层序遍历
102. 二叉树的层序遍历
做一个队列,把二叉树的结点从上往下每层依次输入进队列并按先进先出的原则输出,挺直观的。
from collections import deque
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root == None:
return []
queue = deque([root])
ans = []
while queue:
layer = []
for _ in range(len(queue)):
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
layer.append(cur.val)
ans.append(layer)
return ans
107. 二叉树的层序遍历 II
把上一题的输出反转就是了
class Solution:
def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
if root==None:
return []
queue = collections.deque([root])
ans = []
while queue:
layer = []
for _ in range(len(queue)):
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
layer.append(cur.val)
ans.append(layer)
return ans[::-1]
199. 二叉树的右视图
还是层序遍历,只取每层的最后一个值。
from collections import deque
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if root == None:
return []
queue = deque([root])
ans = []
while queue:
layer = []
for _ in range(len(queue)):
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
layer.append(cur.val)
ans.append(layer[-1])
return ans
637. 二叉树的层平均值
做个均值在输出罢了
from collections import deque
class Solution:
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
if root == None:
return []
queue = deque([root])
ans = []
while queue:
layer = []
for _ in range(len(queue)):
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
layer.append(cur.val)
ans.append(math.fsum(layer)/len(layer))
return ans
429. N 叉树的层序遍历
把对左右子结点的判断变成对子结点的遍历
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if root == None:
return []
queue = collections.deque([root])
ans = []
while queue:
layer = []
for _ in range(len(queue)):
cur = queue.popleft()
for c in cur.children:
queue.append(c)
layer.append(cur.val)
ans.append(layer)
return ans
515. 在每个树行中找最大值
加一个max
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
if root == None:
return []
queue = collections.deque([root])
ans = []
while queue:
layer = []
for _ in range(len(queue)):
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
layer.append(cur.val)
ans.append(max(layer))
return ans
116. 填充每个节点的下一个右侧节点指针
在层序遍历的时候,记录一下前置结点,如果有前置结点就让他指向现在的结点,每层遍历完的时候的最后一个结点指向None
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
if not root:
return root
queue = collections.deque([root])
while queue:
pre = None
for i in range(len(queue)):
cur = queue.popleft()
if pre:
pre.next = cur
pre = cur
if cur.left:
queue.append(cur.left)
if cur.right: # 这一行可以省略
queue.append(cur.right)
cur.next = None
return root
117. 填充每个节点的下一个右侧节点指针 II
和上面一样的
class Solution:
def connect(self, root: 'Node') -> 'Node':
if root == None:
return root
queue = collections.deque([root])
while queue:
pre = None
for i in range(len(queue)):
cur = queue.popleft()
if pre:
pre.next = cur
pre = cur
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
cur.next = None
return root
104. 二叉树的最大深度
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root == None:
return 0
queue = collections.deque([root])
dep = 0
while queue:
dep += 1
for _ in range(len(queue)):
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return dep
111. 二叉树的最小深度
当左右子结点都是None的时候就可以输出深度了
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root == None:
return 0
queue = collections.deque([root])
dep = 0
while queue:
dep += 1
for _ in range(len(queue)):
cur = queue.popleft()
if cur.left == None and cur.right == None:
return dep
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
226. 翻转二叉树
先反转左右结点,再分别反转左右结点里面的子树。
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def inver(root):
if root == None:
return
root.left, root.right = root.right, root.left
inver(root.left)
inver(root.right)
return
if root:
inver(root)
return root
101.对称二叉树
递归法
对左右子结点分别判断,先判断左右对应位置的子结点有None或者都为None的情况,然后如果左右子结点值不同就返回,值相同就以他们的左右结点再进行一次递归比较,比较的时候先外侧再内侧,全都相同的话返回True
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if root == None:
return True
def lequalr(left_root, right_root):
if not left_root==None and right_root==None:
return False
elif left_root==None and not right_root==None:
return False
elif left_root==None and right_root==None:
return True
elif left_root.val != right_root.val:
return False
outside = lequalr(left_root.left, right_root.right)
inside = lequalr(left_root.right, right_root.left)
return outside and inside
return lequalr(root.left, root.right)
迭代法
这里就用层次遍历的方法了,层次遍历的时候判断一下结点是否为None,因为None也需要放进来考虑,不然会存在单层不是镜像列表反转后也相等的情况。
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if root == None:
return True
queue = collections.deque([root])
while queue:
layer = []
for _ in range(len(queue)):
cur = queue.popleft()
if cur:
layer.append(cur.val)
queue.append(cur.left)
queue.append(cur.right)
else:
layer.append(None)
if not layer == layer[::-1]:
return False
return True