二叉树的最大深度
题目详细:LeetCode.104
递归法很容易理解:
- 定义一个全局变量max, 记录二叉树的最大深度
- 在递归函数中增加一个深度参数,表示当前的节点的深度
- 然后对二叉树进行深度优先遍历
- 当遍历到叶子节点时,比较当前节点的深度和记录的最大深度,保持最大值
- 当树遍历完成后,返回记录的最大深度即可
Java解法(递归,深度优先遍历):
class Solution {
private int max = 0;
public int maxDepth(TreeNode root) {
this.dfs(root, 0);
return this.max;
}
public void dfs(TreeNode root, int deep){
if(null == root){
this.max = deep > this.max ? deep : this.max;
return;
}
this.dfs(root.left, deep + 1);
this.dfs(root.right, deep + 1);
}
}
递归法很容易掌握,所以我想尝试用迭代法来解题,但使用前序遍历迭代法来解题好像不是很方便;回到观察问题本身,我发现求二叉树的最大深度,其实就是求叶子节点的最大层数,那么我们也可以利用层序遍历(广度优先遍历)来解题:
Java解法(层序遍历,迭代法,广度优先遍历):
class Solution {
public int maxDepth(TreeNode root) {
return this.bfs(root);
}
public int bfs(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
if(null != root) queue.offer(root);
int deep = 0;
while(!queue.isEmpty()){
deep++;
int len = queue.size();
while(len-- > 0