查找二叉树的最大深度
leetcode104,
根据官方的方法有递归法和广度优先遍历;
- 递归法,如图所示,
- 广度优先遍历,设计数器每次读取一层(类似于二叉树的层次遍历)
#递归法
class Solution:
def maxDepth(self, root):
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
#广度优先
class Solution:
def maxDepth(self, root):
if root is None:
return 0
queue = [root]
ans=0
while queue:
size = len(queue)
while size>0:
node = queue.pop(0)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
size-=1
ans+=1
return ans