终止条件:节点为空时,深度为0
递归条件:节点非空,字节点的深度+1,得到父节点的深度
f(root)=max(f(left)+f(right))+1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
int deep=0;
//终止条件
if(root==null){
return 0;
}
else{
//左子树的深度
int left = maxDepth(root.left);
//右子树的深度
int right = maxDepth(root.right);
//根节点的深度
deep = Math.max(left,right)+1;
}
return deep;
}
}