【LeetCode OJ】Maximum Depth of Binary Tree

时间:2022-04-10 20:57:56

Problem Link:

https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/

Simply BFS from root and count the number of levels. The code is as follows.

# 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