Maximum depth of binary tree#

Levels: level-0
Data structures: tree
Algorithms: dfs

LeetCode

Description#

  • Given a binary tree, find its maximum depth.
  • The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note:

  • A leaf is a node with no children.

Example#

1Given binary tree [3,9,20,null,null,15,7],
2
3    3
4   / \
5  9  20
6    /  \
7   15   7
8
9return its depth = 3.

Python Solution#

 1class TreeNode(object):
 2    def __init__(self, x):
 3        self.val = x
 4        self.left = None
 5        self.right = None
 6
 7
 8class Solution(object):
 9    def maxDepth(self, root):
10        """
11        :type root: TreeNode
12        :rtype: int
13        """
14        return 1 + max(self.maxDepth(root.left), self.maxDepth(
15            root.right)) if root else 0