/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
int result=0;
public int TreeDepth(TreeNode root) {
dfs(root,0);
return result;
}
void dfs(TreeNode root, int currentDeepth){
if(root==null){
return;
}
currentDeepth++;
if(currentDeepth>result){
result=currentDeepth;
}
dfs(root.left,currentDeepth);
dfs(root.right,currentDeepth);
}
}
2021-11-12(JZ55 二叉树的深度)
最新推荐文章于 2024-08-17 08:45:02 发布
这篇博客介绍了如何使用深度优先搜索(DFS)算法计算给定二叉树的深度。通过递归实现的`TreeDepth`方法展示了如何遍历节点并更新最大深度。关键代码展示了TreeNode类和Solution类的交互过程。
摘要由CSDN通过智能技术生成