Maximum Depth of Binary Trees
Problem: Maximum Depth of Binary Trees
The solution is just a complete depth-first search.
Code in Python:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
def dfs(node, depth):
if not node.left and not node.right: return depth+1
left = right = 0
if node.left: left = dfs(node.left, depth+1)
if node.right: right = dfs(node.right, depth+1)
return max(left, right)
return dfs(root, 0)