Search code examples
pythondepth-first-search

How to this python code for max depth using DFS working here?


class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def max_depth(root):
    return root and 1 + max(max_depth(root.left), max_depth(root.right)) or 0

if __name__ =="__main__":
    def build_tree(nodes):
        val = next(nodes)
        if not val or val == 'x': return 
        cur = Node(int(val))
        cur.left = build_tree(nodes)
        cur.right = build_tree(nodes)
        return cur
    root = build_tree(iter(input().split()))
    print(max_depth(root))

Here it's giving the correct answer. But i can't understand how the max_depth function working here. More specifically the 'and' and 'or' operation here.


Solution

  • This expression:

    root and 1 + max(max_depth(root.left), max_depth(root.right)) or 0
    

    is equivalent to:

    1 + max(max_depth(root.left), max_depth(root.right)) if root else 0
    

    This is because and will return the first operand when it is falsy, and the second operand if the first is truthy. The or operand will return its first operand when it is truthy, and its second operand when the first is falsy.

    You can also write it more verbose with separate return statements:

    if root:
        return 1 + max(max_depth(root.left), max_depth(root.right))
    else:
        return 0