104. 二叉树的最大深度
作者:互联网
思路:
层次遍历二叉树,将同一深度的节点值存入temp数组中,统计temp数组的个数,即为二叉树深度
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
'''
层次遍历二叉树+统计统一深度数组个数
'''
if not root:
return 0
res = 0
queue = [root]
while queue:
tem = []
length = len(queue)
for _ in range(length):
node = queue.pop(0)
tem.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if tem:
res += 1
return res
标签:node,right,self,queue,二叉树,深度,104,left 来源: https://blog.csdn.net/qq_49821869/article/details/122786265