102. 二叉树的层序遍历
看完本篇可以一口气刷十道题,试一试, 层序遍历并不难,大家可以很快刷了十道题。
题目链接/文章讲解/视频讲解:https://programmercarl.com/0102.二叉树的层序遍历.html
# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root is None:
return []
result = []
queue = deque()
queue.append(root)
while queue:
level = []
for i in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
226.翻转二叉树 (优先掌握递归)
这道题目 一些做过的同学 理解的也不够深入,建议大家先看我的视频讲解,无论做过没做过,都会有很大收获。
题目链接/文章讲解/视频讲解:https://programmercarl.com/0226.翻转二叉树.html
# 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
def invert(root):
if root is None:
return 0
root.left,root.right = root.right,root.left
invert(root.left)
invert(root.right)
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
invert(root)
return root
101. 对称二叉树 (优先掌握递归)
先看视频讲解,会更容易一些。
题目链接/文章讲解/视频讲解:https://programmercarl.com/0101.对称二叉树.html
# 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
def is_Symmetric(left,right):
if (left is None and right is not None) or (left is not None and right is None):
return False
if left is None and right is None:
return True
if left.val == right.val:
return is_Symmetric(left.left,right.right) and is_Symmetric(left.right,right.left)
else:
return False
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if root is None:
return True
return is_Symmetric(root.left,root.right)
标签:None,right,self,层序,Day15,二叉树,root,left
From: https://www.cnblogs.com/forrestr/p/18234150