- 101:对称二叉树
python
复制代码
# 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 dfs(node, level, res):
if len(res) == level:
res.append([])
if not node:
res[level].append('None')
else:
res[level].append(node.val)
dfs(node.left, level + 1, res)
dfs(node.right, level + 1, res)
res = []
level = 0
dfs(root, level, res)
for i in res:
if i[::-1] != i:
return False
return True
- 100:相同的树
python
复制代码
# 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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
def dfs(node, level, res):
if len(res) == level:
res.append([])
if not node:
res[level].append('None')
else:
res[level].append(node.val)
dfs(node.left, level + 1, res)
dfs(node.right, level + 1, res)
res1 = []
res2 = []
level = 0
dfs(p, level, res1)
dfs(q, level, res2)
return res1 == res2
- 559:N叉树的最大深度
python
复制代码
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
def dfs(node, level, res):
if not node:
return
if len(res) == level:
res.append([])
res[level].append(node.val)
for child in node.children:
dfs(child, level + 1, res)
res = []
level = 0
dfs(root, level, res)
return len(res)
- 111:二叉树的最小深度
python
复制代码
# 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 minDepth(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if not node:
return 0
if node.left and not node.right:
return 1 + dfs(node.left)
elif not node.left and node.right:
return 1 + dfs(node.right)
elif not node.left and not node.right:
return 1
elif node.left and node.right:
return 1 + min(dfs(node.left), dfs(node.right))
res = dfs(root)
return res