Question Link:
https://leetcode.com/problems/maximum-depth-of-binary-tree/
Simply BFS from root and count the number of levels. The code is as follows.
[-]
Python code accepted by LeetCode OJ
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
"""
Use BFS from root, and count the steps
"""
if not root:
return 0
count = 0
q = [root]
while q:
count += 1
new_q = []
for node in q:
if node.left:
new_q.append(node.left)
if node.right:
new_q.append(node.right)
q = new_q
return count