特别值得注意的地方是,ans和max的作用
- 其中max是用来比较记录答案,即最大值
- 而ans是用来记录每次的递增过程,每条路的深度。返回上一个节点的时候要-1,因为它是全局变量
public class Solution {
//变量定义了在这里,全局变量
int ans=1;
int max=0;
public int TreeDepth(TreeNode root) {
if(root==null)
{
ans=ans-1;
if(max<ans)
{
max=ans;
// System.out.println("max"+max);
}
// System.out.println("ans"+ans);
return 0;
}
if(root!=null)
{
ans=ans+1;
TreeDepth(root.left);
}
if(root!=null)
{
ans=ans+1;
TreeDepth(root.right);
}
ans=ans-1;
return max;
}
}