LeetCode 104二叉树的最大深度
题目

解析
写一个递归函数,返回最大深度
代码
/**
* 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) {
if(root==null)return 0;
else if(root.left==null&&root.right==null)return 1;
return depth(root,1);
}
int depth(TreeNode tree,int index){
int leftCount=0;
int rightCount=0;
if(tree.left!=null){
leftCount=depth(tree.left,index+1);
}
if(tree.right!=null){
rightCount=depth(tree.right,index+1);
}
if(tree.left==null&&tree.right==null){
return index;
}
return (leftCount>rightCount)?leftCount:rightCount;
}
}
本文详细解析了LeetCode104题——求解二叉树的最大深度,通过递归函数实现,提供了完整的代码示例,帮助读者理解和掌握二叉树深度的计算方法。
1045

被折叠的 条评论
为什么被折叠?



