您的位置:首页 > 其它

Maximum Depth of Binary Tree--LeetCode

2017-09-14 19:30 375 查看

1.题目

Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

2.题意

给定一个二叉树, 找到它的最大深度。

最大深度是沿最长路径的节点数,从根节点向下到最远的叶节点。

3.分析

1)递归:采用DFS返回左子树与右子树中较大的深度加1即可

时间复杂度 O(n),空间复杂度 O(logn)

2)非递归:采用BFS进行层序遍历,总层数即为二叉树最大深度

使用其他遍历同样需要O(n)的复杂度,但层序遍历更直观

4.代码

1)递归

class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr)
return 0;

int left = maxDepth(root->left);
int right = maxDepth(root->right);

return left > right ? left + 1 : 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 == nullptr)
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息