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;
}
}