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.
Example
Given a binary tree as follow:
1
/ \
2 3
/ \
4 5
The maximum depth is 3.
Python:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
'''
# divide and conquer
def maxDepth(self, root):
if root is None:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return 1 + max(left, right)
'''
'''
# non recursion
def maxDepth(self, root):
if root is None:
return 0
stack = [root]
depth = 0
while stack:
next = []
depth += 1
for item in stack:
if item.left:
next.append(item.left)
if item.right:
next.append(item.right)
stack = next
return depth
'''
result = float('-inf')
def maxDepth(self, root):
if root is None:
return 0
self.helper(root, 1)
return self.result
def helper(self, root, depth):
if root.left is None and root.right is None:
self.result = max(self.result, depth)
if root.left:
self.helper(root.left, depth + 1)
if root.right:
self.helper(root.right, depth + 1)