输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
具体代码实现如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
// 二叉树的后序遍历(DFS)
if(root == null) return 0;// 递归出口条件
int l = maxDepth(root.left);// 递归遍历左子树的深度
int r = maxDepth(root.right);// 递归遍历右子树的深度
return Math.max(l, r) + 1;// 比较左右子树中最深的子树长度,再加上根节点那一层
/*
//bfs 层次遍历,需要借助队列来实现
if(root == null) return 0; // 空判断
Queue<TreeNode> queue = new LinkedList<>(); // 创建队列来实现层次遍历
int res = 0; // 记录深度
queue.add(root);// 先将根节点接入队列
while(!queue.isEmpty()){// 当队列为空时 跳出循环
res++;// 记录层数
int n = queue.size();// 记录每层的个数
for(int i = 0; i < n; i++){
TreeNode cur = queue.poll();
if(cur.left != null) queue.add(cur.left);
if(cur.right != null) queue.add(cur.right);
}
}
return res;
*/
}
}
人生若只如初见,何事秋风悲画扇。
等闲变却故人心,却道故人心易变。
-----------纳兰性德
小白寄语:学如逆水行舟,不进则退。