leetcode Maximum Depth of Binary Tree
2015-09-16 09:23
295 查看
Maximum Depth of Binary Tree
My SubmissionsQuestion
Solution
Total Accepted: 85301 Total
Submissions: 188185 Difficulty: Easy
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.
Show Tags
Show Similar Problems
Have you met this question in a real interview?
Yes
No
相当于广度遍历,然后加一个统计深度的变量就好。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root)
{
int result=0;
vector<TreeNode*> levelNode;
if (root == NULL)
return 0;
int levelNum = 1, nextlevel = 0;
levelNode.push_back(root);
while (!levelNode.empty())
{
result++;
for (int i = 0; i < levelNum; i++)
{
if (levelNode[0]->left != NULL)
{
nextlevel++;
levelNode.push_back(levelNode[0]->left);
}
if (levelNode[0]->right != NULL)
{
levelNode.push_back(levelNode[0]->right);
nextlevel++;
}
levelNode.erase(levelNode.begin());
}
levelNum = nextlevel;
nextlevel = 0;
}
return result;
}
};
相关文章推荐
- **百合测试**
- 如何在 Ubuntu 15.04 系统中安装 Logwatch
- 关于一些post请求的汇总
- 沙朗javascript(两)正则表达式
- linux 常用命令参数集合(一)
- CUDA DLL 开发流程
- 13 种激励程序员的方法
- 盒子模型的宽度计算问题, 有什么问题,及解决方案
- Redis --- 常用命令
- 突然觉得有必要写一本书—《某种商品的业务学习手册国外进口》
- 【iOS】iOS Error Domain=NSCocoaErrorDomain Code=3840 "未能完成操作。(“Cocoa”错误 3840。)"
- 实现读取文本数据,在将数据导入mysql
- Struts2中访问web元素的四种方式及前台jsp页面获取后台值的方式
- JS实现不规则TAB选项卡效果代码
- 如何在 Ubuntu 15.04 系统中安装 Logwatch
- 2015年9月15号工作总结
- 宁以const引用传递代替按值传递(内置类型除外)
- Spring配置文件加载properties文件
- 宁以const引用传递代替按值传递(内置类型除外)
- hdu2005