I'm trying to understand how this code works:
# 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 inorderTraversal(self, root: Optional[TreeNode], result: List[int] = None) -> List[int]:
if result is None:
result = []
if root:
self.inorderTraversal(root.left, result)
result.append(root.val)
self.inorderTraversal(root.right, result)
return result
Suppose our tree is [5, 8, 7] (i.e., 5 is the root, its left daughter is 8 and its right daughter is 7). First, the root is given as the input. The empty results list is created. The root is not None, so the body of the if statement is executed. The first line of the if statement is supposed to call the traversal function on the left daughter of the root, i.e., on root.left. So we're back to the line "if result is None". This first if statement is skipped. For the second if statement, root.left is true, so the statement in the body of the second if statement is executed. Namely, the function calls itself for a second time, this time on the argument root.left.left. So we go back to the line "if result is None". This first if statement is skipped again. Now we get to the line "if root.left.left". But root.left.left is None, so we should not execute the code in the body of the statement and we should return "result". Where's my mistake?