1. 终止条件: 当进入叶子节点后,再进入子节点,即为空,没有深度可言,返回0.
  2. 返回值: 每一级按照上述公式,返回两边子树深度的最大值加上本级的深度,即加1.
  3. 本级任务: 每一级的任务就是进入左右子树,求左右子树的深度。

具体做法:

step 1:对于每个节点,若是不为空才能累计一次深度,若是为空,返回深度为0.
step 2:递归分别计算左子树与右子树的深度。
step 3:当前深度为两个子树深度较大值再加1。

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/

public class Solution {
    public int TreeDepth(TreeNode root) {
        //dfs  深度有点搜索
        if(root==null){
            return 0;//到达根节点 此时深度为0
        }
        int maxDepth=0; //定义最大深度
        int leftMax=TreeDepth(root.left)+1; //求左子树最大深度
        int rightMax=TreeDepth(root.right)+1; //求取右子树最大深度
        maxDepth =  Math.max(leftMax,rightMax);
        return maxDepth;
    }
}