日野弥生:勉強しよう
LeetCode 965 - 单值二叉树
发表于2025年03月02日
递归解题,整体思路还是较为清晰的。遍历每个节点和根节点的值比对,因为原题已经确认根节点不为空。
class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
rootVal = root.val
def isUnivalTreeIMPL(root: Optional[TreeNode]) -> bool:
if root:
if root.val != rootVal:
return False
left, right = True, True
if root.left:
left = isUnivalTreeIMPL(root.left)
if root.right:
right = isUnivalTreeIMPL(root.right)
return left and right
return isUnivalTreeIMPL(root)
注意,其实,如果遍历到的结点为空时,是应该直接返回True的,这样可以简化代码。
class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
if not root:
return True # 空树是单值二叉树
rootVal = root.val
def isUnivalTreeIMPL(root: Optional[TreeNode]) -> bool:
if not root:
return True
if root.val != rootVal:
return False
return isUnivalTreeIMPL(root.left) and isUnivalTreeIMPL(root.right)
return isUnivalTreeIMPL(root)