思路:使用递归,分别计算节点的左右子树的深度,返回其中的最大值
//前序遍历二叉树,计算深度
public static int maxDepth_2(TreeNode root){
int depth=0;
return preorder(root,depth);
}
public static int preorder(TreeNode root,int depth){
if(root==null) return depth;
//分别计算左右子树的深度,返回最大值
int left=preorder(root.left,depth)+1;
int right=preorder(root.right,depth)+1;
depth=Math.max(left,right);
return depth;
}