二叉树的层次遍历
2017-04-29 22:47
190 查看
一、问题描述
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
二、样例
给一棵二叉树
返回他的分层遍历结果:
三、思路
将每层的节点入对然后依次出队,再将出队节点的下一层保存,并将出队节点存入向量中,层层进行,直到最后一层。
四、代码
/**
* 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
}
};
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
二、样例
给一棵二叉树
{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
}
};
相关文章推荐
- LeetCode103 BinaryTreeZigzagLevelOrderTraversal(二叉树Z形层次遍历) Java题解
- Java数据结构--- 二叉树(二叉排序树,层次遍历二叉树节点)
- 二叉树按层次遍历--队列实现
- Java二叉树按层次遍历,换行输出
- 例题6-7 二叉树的层次遍历 UVa 122 Trees on the level
- 用递归方法对二叉树进行层次遍历
- 二叉树的层次遍历 II - C++
- 二叉树的遍历:先序,中序,后序,递归,非递归,层次遍历
- 层次遍历二叉树
- [算法-java] 数组转二叉树_(层次遍历)
- 数据结构 学习笔记(四):树(上):树的表示,二分查找,二叉树,先中后层次遍历
- java操作二叉树:构建二叉树;前序、中序、后续、层次遍历
- 编写按层次遍历二叉树的算法
- LintCode-剑指Offer-(70)二叉树的层次遍历Ⅱ
- 【遍历二叉树】05二叉树的层次遍历II【Binary Tree Level Order Traversal II】
- LeetCode(Binary Tree Level Order Traversal, 2,Zigzag)二叉树的层次遍历
- 二叉树层次遍历
- C++实现链式二叉树,操作包括初始化二叉树、前序遍历、中序遍历、后序遍历、层次遍历
- 二叉树递归求高度,非递归求高度,层次遍历
- 二叉树之层次遍历(js)