题目
截图自官方
代码
广度优先解法等后面专门练广度优先
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// 递归,只可意会不可言传
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
// 这样等于额外计算了递归很多次。超时了
// return maxDepth(root.left)>=maxDepth(root.right)?maxDepth(root.left)+1:maxDepth(root.right)+1;
// 修改下
int ans=Math.max(maxDepth(root.left),maxDepth(root.right));
return ans+1;
}
// 广度优先解法,后面专门练广度优先解法
}