思路:
深度优先遍历
代码:
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
分解:
1)核心代码:
比较左右子树中较大的一个,再+1
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
复杂度分析:
时间复杂度:O(N)最差情况下要遍历N个节点
空间复杂度:O(N)最差情况下退化为链表