Appearance
55-I-二叉树的深度
题目描述
https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
注意:本题与主站 104 题相同:https://leetcode.cn/problems/maximum-depth-of-binary-tree/
来源:力扣(LeetCode) 链接: 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路分析
基本思路: 深度优先搜索,每次递归加1,递归返回减1,中途缓存最大值 注意使用先序遍历: 根左右 或者 根右左,都可以
实现代码
csharp
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int maxDepth;
private int curDepth;
private void dfs(TreeNode cur){
if(cur == null){ return;}
curDepth+=1;
maxDepth = curDepth > maxDepth ? curDepth : maxDepth;
dfs(cur.left);
dfs(cur.right);
curDepth-=1;
}
public int MaxDepth(TreeNode root) {
dfs(root);
return maxDepth;
}
}
直接将当前深度传入也可以
实现代码2:复习
csharp
public class Solution {
int maxDepth = 0;
private void dfs(TreeNode cur, int curDepth){
if(cur == null){
return;
}
curDepth++;
maxDepth = Math.Max(curDepth,maxDepth);
dfs(cur.left,curDepth);
dfs(cur.right,curDepth);
}
public int MaxDepth(TreeNode root) {
dfs(root,0);
return maxDepth;
}
}
实现代码3:直接递归计算左右节点
csharp
public class Solution{
public int MaxDepth(TreeNode root){
if(root == null){
return 0;
}
int leftMax = MaxDepth(root.left);
int rightMax = MaxDepth(root.right);
return Math.Max(leftMax,rightMax)+1;
}
}
实现代码4: BFS 每一层计数加1
csharp
public class Solution{
public int MaxDepth(TreeNode root){
if(root == null){
return 0;
}
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
int depth = 0;
while(queue.Count > 0){
int count = queue.Count;
for(int i=0; i<count; i++){
TreeNode cur = queue.Dequeue();
if(cur.left != null){
queue.Enqueue(cur.left);
}
if(cur.right != null){
queue.Enqueue(cur.right);
}
}
depth++;
}
return depth;
}
}
AlgoPress