题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
总思路
树的遍历方式总体分为两类:深度优先搜索(DFS)、广度优先搜索(BFS);
常见的 DFS : 先序遍历、中序遍历、后序遍历; 常见的 BFS : 层序遍历。
解题思路1: 深度优先搜索(DFS)
如果我们知道了左子树和右子树的最大深度L和R,那么该二叉树的最大深度即为 m a x ( l , r ) + 1 max(l,r)+1 max(l,r)+1,而左子树和右子树的最大深度又可以以同样的方式进行计算。
由此可得:递归计算
代码1:
Python代码:
class Solution(object):
def maxDepth(self, root):
if root is None:
return 0
else:
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left, right) + 1
Java代码:
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null)
return 0;
return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
}
}
解题思路2: 广度优先搜索(BFS)
- 树的层序遍历 / 广度优先搜索往往利用 队列 实现。
- 关键点: 每遍历一层,则计数器 +1 ,直到遍历完成,则可得到树的深度。
代码2:
class Solution:
def maxDepth(self, root):
if not root: return 0
queue, res = [root], 0
while queue:
tmp = [] # 每次都为空
for node in queue:
if node.left: tmp.append(node.left)
if node.right: tmp.append(node.right)
queue = tmp
res += 1
return res
题目来源:
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/