'class attributes and recursion of function in python

I just solved problem on leetcode and I can't understand one thing in this code:

# 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))

As I understand, root is a TreeNode object and that's why it should have all the attributes of TreeNode as val, left, right. In the last string we use attributes left and right of root. But when I wrote if not root.val it returned an error Nonetype object has no attribute val. Why in return we can use attributes of root, but we can't use if not root.val?



Solution 1:[1]

Its not what you say. The code is not using the attributes of root, it is essentially querying root, asking: "Are you a TreeNode, or None?".

If it is None, then it executes return 0.

If it is not None, then it must be a TreeNode, and then it will have the left and right attributes.

I'm sure that there may be many instances of TreeNode with attribute val == 0.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 quamrana