[LeetCode]104 - Maximum Depth of Binary Tree(easy) - python

原文链接https://blog.csdn.net/coder_orz/article/details/51337420

problem description:

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.
在这里插入图片描述

思路方法:

思路一

深度优先搜索(DFS),递归求解

①如果只有一个根节点,那么树的深度为1.
②如果只有根节点和左子树,那么树的深度为为左子树的深度+1,如果只有根节点和右子树,那么树的深度为右子树的深度+1。
③如果既有左子树和右子树,那么树的深度为左右子树中深度的较大值+1。

我们可以利用递归,不断的将不同层级的左子树和右子树调入到深度函数中,利用max函数找出他们两个中的最大深度,然后加上根节点的 1 就是整个树的最大深度。

注意:要考虑到树为空的特殊情况

代码:
在这里插入图片描述

思路二

广度优先搜索(BFS),利用队列求解。

每次先把不同层级的根节点加进来,然后根据根节点把它的左右子树加进来,再把根节点删除掉,深度自增 1,这样循环递归,直到遍历完整棵树,最后返回树的深度。(注意结合队列数据传输模型的特点来分析)

代码:
在这里插入图片描述

说明
作为这个问题的对比,类似问题:
111. Minimum Depth of Binary Tree [easy] (Python) - Coder_Orz的博客 - CSDN博客 https://blog.csdn.net/coder_orz/article/details/51337522

猜你喜欢

转载自blog.csdn.net/Arno_Pei/article/details/87952121
今日推荐