问题描述:
Given the root of a binary tree, return its maximum depth.
A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
求二叉树最大深度
思路:
某一点深度 = max(左子树深度,右子树深度)+1
class Solution {
public int maxDepth(TreeNode root) {
int depth;
if (root==null){
return 0;
}
depth = 1+ Math.max(maxDepth(root.left), maxDepth(root.right));
return depth;
}
}
问题/bug反思:当时递归终止条件写的是:
if ((root.leftnull)&&(root.rightnull)){
return 1;
}
这里忽略了root不存在的情况,所以索性把递归终止条件设为
if (root==null){
return 0;
}
时间复杂度:O(N)