/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
public int maxDepth(TreeNode root) {
//最大深度可以设置一个max(int),递归的方法获取每个节点的子节点,如果left和right都是空,那么就与max作对比,记录下最大的即可。
if(root==null){
return 0;
}
calDepth(root,0);
return max;
}
public void calDepth(TreeNode node,int nowDepth){
if(node.right==null && node.left==null){
max= max<nowDepth+1 ? nowDepth+1 : max;
}
if(node.left!=null){
calDepth(node.left,nowDepth+1);
}
if(node.right!=null){
calDepth(node.right,nowDepth+1);
}
}
}