二叉树的层次遍历
来源:互联网 发布:西部数码域名管理 编辑:程序博客网 时间:2024/06/05 11:29
一、问题描述
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
二、样例
给一棵二叉树 {3,9,20,#,#,15,7}
:
3 / \9 20 / \ 15 7
返回他的分层遍历结果:
[ [3], [9,20], [15,7]]
三、思路将每层的节点入对然后依次出队,再将出队节点的下一层保存,并将出队节点存入向量中,层层进行,直到最后一层。
四、代码
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public:
vector<vector<int>> levelOrder(TreeNode *root) {
vector<vector<int>> result;
queue<TreeNode*>q;
vector<int> level; //每层结果
int size,i;
TreeNode* p;
if(root==NULL) return result;
q.push(root); //入队
while(!q.empty())
{ //队列中有几个元素就依次遍历每个元素的左右结点
level.clear();
size=q.size();
for(i=0; i<size; i++)
{
p=q.front(); //队首元素值赋给p
q.pop(); //出队
level.push_back(p->val);
if(p->left)
{ //依次压入左右结点元素
q.push(p->left);
}
if(p->right)
{
q.push(p->right);
}
}
result.push_back(level); //添加每层数据
}
return result;
// write your code here
}
};
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历!!!
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- Cocos2d-X官方Demo---1.ActionManager
- 【python】解析中英文进阶
- JS跨域解决方案
- Tensorflow读取数据2-tfrecord
- Nessus漏洞扫描工具安装
- 二叉树的层次遍历
- kaggle入门篇二【Titanic】
- 【bzoj1677】[Usaco2005 Jan]Sumsets 求和
- 五.SpringMVC+MyBatis搭建安全与性能
- 116. Populating Next Right Pointers in Each Node
- IntelliJ IDEA 注册
- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-o2julgbe/xgboost/
- 《程序员修炼之道》笔记(一)
- 地狱飞龙 [simpson][积分]