二叉树的层次遍历
来源:互联网 发布:linux tee 用法 编辑:程序博客网 时间:2024/06/07 10:38
样例
给一棵二叉树 {3,9,20,#,#,15,7} :
3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
* @param root : The root of binary tree.
* @return : buttom-up level order a list of lists of integer
*/
public:
vector<vector<int> > levelOrder(TreeNode *root) {
// write your code here
vector<vector<int> > vec;
if(root==NULL)
return vec;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
vector<int> it;
while(!q.empty())
{
TreeNode* p = q.front();
q.pop();
if(p!=NULL)
{
it.push_back(p->val);
if(p->left!=NULL)
q.push(p->left);
if(p->right!=NULL)
q.push(p->right);
}
else
{
if(!it.empty())
{
vec.push_back(it);
it.clear();
q.push(NULL);
}
}
}
return vec;
}
};
给一棵二叉树 {3,9,20,#,#,15,7} :
3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
class Solution {
/*** @param root : The root of binary tree.
* @return : buttom-up level order a list of lists of integer
*/
public:
vector<vector<int> > levelOrder(TreeNode *root) {
// write your code here
vector<vector<int> > vec;
if(root==NULL)
return vec;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
vector<int> it;
while(!q.empty())
{
TreeNode* p = q.front();
q.pop();
if(p!=NULL)
{
it.push_back(p->val);
if(p->left!=NULL)
q.push(p->left);
if(p->right!=NULL)
q.push(p->right);
}
else
{
if(!it.empty())
{
vec.push_back(it);
it.clear();
q.push(NULL);
}
}
}
return vec;
}
};
0 0
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历!!!
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- Java中堆与栈的区别(仅做个人知识储备)
- Ubuntu-搭建简易Git-Server
- python小程序--实现对文本的汉字统计
- VB如何触发焦点事件和失去焦点事件
- PAT试题1001题
- 二叉树的层次遍历
- 基于ARM 的led循环点亮C程序
- 重新初识java
- LeetCode | 19. Remove Nth Node From End of List
- 多项式乘法计算
- python-cookbook学习笔记六
- windows下beego安装
- git的使用
- 儿童阅读书籍网站