层序遍历
102.二叉树的层序遍历
解法1:迭代
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
# method 1
if not root:
return None
res = []
queue = [root]
while queue:
n = len(queue)
temp = []
for _ in range(n):
node = queue.pop(0)
temp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(temp)
return res
解法2:递归
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
# method 2
res = []
def dfs(root,depth):
if not root:
return None
if len(res) == depth:
res.append([])
res[depth].append(root.val)
if root.left:
dfs(root.left,depth+1)
if root.right:
dfs(root.right,depth+1)
dfs(root,0)
return res
226.翻转二叉树
解法1:递归
# 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]:
# method 1
if not root:
return None
root.left,root.right = root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
解法2:迭代
# 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]:
# method 2
if not root:
return None
queue = [root]
while queue:
n = len(queue)
for _ in range(n):
node = queue.pop(0)
node.left, node.right = node.right,node.left
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.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:
if not root:
return True
def dfs(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 dfs(left.left,right.right) and dfs(left.right,right.left)
return dfs(root.left,root.right)