1
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.

1
  • 1
    What do you understand about it? Commented Oct 8, 2020 at 18:18

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

This is definitely a much better answer. Nice :)
1

The and is used to check if the root is not None. So it is like doing:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.