1. 题目
给定一个二叉树,找到它的最大深度。
2. 分析
最大深度是沿最长路径的节点数,从根节点向下到最远的叶节点。
1:递归,采用DFS返回左子树与右子树中较大的深度加1即可
时间复杂度 O(n),空间复杂度 O(logn)
2:非递归,采用BFS进行层序遍历,总层数即为二叉树最大深度
使用其他遍历同样需要O(n)的复杂度,但层序遍历更直观
3. 代码
1)递归
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return max(left, right) + 1;
// return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
若是写成
if(maxDepth(root->left) > maxDepth(root->right))
return maxDepth(root->left) + 1;
else
return maxDepth(root->right) + 1;
则会因maxDepth调用次数过多导致Submission Result: Time Limit Exceeded
2)非递归
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
queue<TreeNode*> q;
q.push(root);
int level = 0;
while(!q.empty())
{
++level;
int len = q.size();
for(int i = 0; i < len; ++i)
{
TreeNode *node = q.front();
q.pop();
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
}
return level;
}
};