本文是力扣LeeCode-104. 二叉树的最大深度 学习与理解过程,本文仅做学习之用,对本题感兴趣的小伙伴可以出门左拐LeeCode。
给定一个二叉树 root ,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:3
示例 2:
输入:root = [1,null,2]
输出:2
提示:
树中节点的数量在 [0, 104] 区间内。
-100 <= Node.val <= 100
思路
做二叉树的题目,首先需要确认的是遍历顺序,这道题,可以用后序遍历:左右中,也可以用前序遍历:中左右,笔者这里采用后序遍历,因为理解和书写更适合刷题宝宝。
- 确定递归函数的参数和返回值:
int getDepth(TreeNode node) - 确定终⽌条件:
if(node==null)return 0; - 确定单层递归的逻辑:
int leftHeight = getDepth(node.left); //左
int rightHeight = getDepth(node.right); //右
int height = 1+Math.max(leftHeight,rightHeight); //中
return height;
代码实现
class Solution {
public int maxDepth(TreeNode root) {
return getDepth(root);
}
private int getDepth(TreeNode node){
if(node==null)return 0; //遇到叶子结点返回
int leftHeight = getDepth(node.left); //递归返回遍历到当前节点node的左子树的深度
int rightHeight = getDepth(node.right); //递归返回遍历到当前节点node的右子树的深度
int height= 1+Math.max(leftHeight,rightHeight); //取当前节点下最深的左子树或右子树,并+1(当前节点)
return height;
}
}
优化代码实现
class Solution {
public int maxDepth(TreeNode root) {
if(root==null)return 0;
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}
}
最终要的一句话:做二叉树的题目,首先需要确认的是遍历顺序
大佬们有更好的方法,请不吝赐教,谢谢










![P1042 [NOIP2003 普及组] 乒乓球————C++](https://img-blog.csdnimg.cn/direct/f3e3a00cd8184864bcb39e77a5a88e1a.png)


![[②C++ Boost]: Boost库编译,arm交叉编译方法](https://img-blog.csdnimg.cn/direct/2c99c2775e8a419aa83a8c7fb2c04bfc.png)





