您的位置:首页 > 其它

leetcode--Maximum Depth of Binary Tree

2017-05-02 21:12 429 查看
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.

Subscribe to see which companies asked this question.

解题思路:

从根节点root开始,若为NULL则树的深度为0.

若root不为NULL,建立一个队列,放入root,开始循环.

计数自增1(count++),遍历整个队列,每检查一个元素;

若该元素的左节点不为NULL,则将该左节点放入队列;

若该元素的右节点不为NULL,则将该右节点放入队列;

从队列中删除该元素,若队列为空,退出循环

返回计数count

代码:

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

int count= 0;
queue<TreeNode *> q;
q.push(root);
while(!q.empty())
{
count++;
for(int i = 0, n = q.size(); i < n; ++ i)
{
TreeNode *p = q.front();
q.pop();

if(p -> left != NULL)
q.push(p -> left);
if(p -> right != NULL)
q.push(p -> right);
}
}

return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: