# Definition for a binary tree node.classTreeNode:def__init__(self, x):
self.val = x
self.left =None
self.right =NoneclassSolution:defmaxDepth(self, root: TreeNode)->int:ifnot root:return0
q =[]
q.append(root)
ans =0while q:
tmp =[]for i in q:if i.left:
tmp.append(i.left)if i.right:
tmp.append(i.right)
ans +=1
q = tmp
return ans
递归
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:defmaxDepth(self, root: TreeNode)->int:ifnot root:return0else:
l = self.maxDepth(root.left)+1
r = self.maxDepth(root.right)+1returnmax(l, r)