class python 中函数的属性和递归

class attributes and recursion of function in python

我刚刚在 leetcode 上解决了问题,但我无法理解这段代码中的一件事:

# 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 not root:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

据我了解,root 是一个 TreeNode 对象,这就是为什么它应该具有 TreeNode 的所有属性,如 valleftright。在最后一个字符串中,我们使用根的属性 leftright。但是当我写if not root.val时它返回了一个错误Nonetype object has no attribute val。为什么在return中可以使用root的属性,而不能使用if not root.val

不是你说的。代码没有使用root的属性,本质上是在查询root,询问:"Are you a TreeNode, or None?".

如果是None,则执行return 0

如果不是None那么一定是TreeNode,然后就会具有 leftright 属性。

我确定可能有很多 TreeNode 属性 val == 0 的实例。