[Python] Why using 'or' here for tree traversing is faster?

Discussão em 'Python' iniciado por Stack, Setembro 9, 2025.

  1. Stack

    Stack Membro Participativo

    I am solving for the Leetcode problem 104. Maximum Depth of Binary Tree. What I realize is that for the line findDepth(node.left, depth+1) or findDepth(node.right, depth+1), if I change it to findDepth(node.left, depth+1) \n findDepth(node.right, depth+1), though the output is correct, the runtime increases from 1ms to 7ms. I am confused since the findDepth function will always return None, thus both sides of the 'or' will be executed anyway.

    class Solution(object):
    def maxDepth(self, root):
    """
    :type root: Optional[TreeNode]
    :rtype: int
    """
    self.max = 0

    def findDepth(node, depth):
    if not node:
    return None
    if depth > self.max:
    self.max = depth
    findDepth(node.left, depth+1) or findDepth(node.right, depth+1)

    findDepth(root, 1)
    return self.max


    I will like to know the differences between the two lines(with and without or).

    Continue reading...

Compartilhe esta Página