# 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 maxDepth(self, root: Optional[TreeNode]) -> int:
if root==None:
return 0
else:
return max(self.maxDepth(root.left), self.maxDepth(root.right))+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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
# 以相同的方式同时遍历两棵二叉树
# 返回false:遇到有值的节点时,如果值不相等 / 或者其中一个为空另一个不为空
# 先审视一下根节点
if p==None and q==None: #同时为空是可以的
return True
if p==None or q==None: #一个为空,另一个不空,这不行
return False
if p.val!=q.val: #如果上边两种情况都没有返回,那俩都不为空,此时如果值不相等,这不行
return False
#根节点暂且满足条件(都不为空且值相等),接下来检查一下左右子树的返回情况
left = self.isSameTree(p.left, q.left)
right = self.isSameTree(p.right, q.right)
# 左右必须完全一样才能返回True
if left and right:
return True
else:
return False
# 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 copyTrees(self, p, q):
# p指向左子树的根节点,q指向右子树的根节点
# 刚开始root节点p、q指向相同,相当于左右重合,此时也是满足对称的
if p==None and q==None:
return True
if p==None or q==None:
return False
if p.val!=q.val:
return False
# 根节点暂时满足条件(都不为空且值相等),接下来检查左右子树的返回情况
p_left = self.copyTrees(p.left, q.right) # 以p的左为基准,和q的右对比
p_right = self.copyTrees(p.right, q.left) # 以p的右为基准,和q的左对比
if p_left and p_right:
return True
else:
return False
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
res = self.copyTrees(root, root) # 在这个函数里实现和上题类似的过程
return res
# 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 root==None:
return None
# 其他只要是非空的节点,我们就等着返回交换后的左右子树
left = self.invertTree(root.right)
right = self.invertTree(root.left)
root.left = left
root.right = right
return root
持续更新中……