【代码随想录训练营】【Day 18】【二叉树-2】| 层序遍历-10, Leetcode 226, 101
需强化知识点
- 226 翻转二叉树
题目
层序遍历
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
levels = []
self.helper(root, 0, levels)
return levels
def helper(self, node, level, levels):
if not node:
return
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
self.helper(node.left, level + 1, levels)
self.helper(node.right, level + 1, levels)
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
queue = collections.deque([root])
result = []
while queue:
level = []
for _ in range(len(queue)):
cur = queue.popleft()
level.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
result.append(level)
return result
226. 翻转二叉树
- 总体思路:交换左右节点
- 递归法:前序和后序,后序会在左子树上翻转两次
# 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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# if not root:
# return root
# left = self.invertTree(root.left)
# right = self.invertTree(root.right)
# root.left, root.right = root.right, root.left
# return root
if not root:
return root
que = collections.deque([root])
while que:
for _ in range(len(que)):
cur = que.popleft()
cur.left, cur.right = cur.right, cur.left
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
return root
101. 对称二叉树
- 本题的核心,是要比较左右子树
# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
def compare(left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val != right.val:
return False
return compare(left.left, right.right) and compare(left.right, right.left)
if not root:
return True
return compare(root.left, root.right)