- Binary Tree Level Order Traversa
- Binary Tree Level Order Traversa
- Binary Tree Level Order Traversa
- Binary Tree Level Order Traversa
- Binary Tree Level Order Traversa
- Binary Tree Level Order Traversa
- Binary Tree Level Order Traversa
- Binary Tree Level Order Traversa
- Binary Tree Level Order Traversa
- Binary Tree Level Order Traversa
题目描述
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree{3,9,20,#,#,15,7},
return its level order traversal as:
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
题目大意
层序遍历二叉树
把遍历结果保存在一个二维数组中
一层保存在二维数组的一行中
思路
刚开始用的时候感觉vector不好用,现在越用感觉越好用
用队列实现二叉树的层序遍历
关键是定义两个指针,指向每一层的当前结点和最后一个结点
每当一层遍历完毕,层数加一,并且给vector二维数组增加新的一行。
代码
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
/*
结构体定义
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/*
具体实现算法
*/
typedef TreeNode* tree;
vector<vector<int> > levelOrder(TreeNode *root)
{
vector<vector<int > > vec; // 定义二维数组,其中元素为int类型
if(root == NULL)return vec;
queue<tree> qu; // 保存二叉树层序遍历结点的指针
qu.push(root);
tree now = root; // 当前结点指针
tree last = root; // 保存每层最后一个结点的指针
int lev = 0; // 保存层的序号
vector<int> vt; // 二维数组的新一行
vec.push_back(vt); // 给二维数组加一行
while(!qu.empty())
{
now = qu.front();
qu.pop();
vec[lev].push_back(now->val);
if(now->left != NULL)qu.push(now->left);
if(now->right != NULL)qu.push(now->right);
if(last==now && !qu.empty())
{ // 表示当前层已遍历完毕
lev++; // 层数序号加一
last = qu.back(); // last指向新的一层的最后一个元素
vec.push_back(vt); // 给二维数组加一行
}
}
return vec;
}
// 二叉树的层序遍历算法
void print(TreeNode *root)
{
queue<tree > qu;
qu.push(root);
while(!qu.empty())
{
tree now = qu.front();
qu.pop();
cout<<now->val<<endl;
if(now->left != NULL)qu.push(now->left);
if(now->right != NULL)qu.push(now->right);
}
}
int main()
{
tree tr;
tr = new TreeNode(1);
tree t1;
t1 = new TreeNode(2);
tr->left = t1;
tree t2;
t2 = new TreeNode(3);
tr->right = t2;
tree t3;
t3 = new TreeNode(4);
t2->left = t3;
vector<vector<int > > vec;
//print(tr);
vec = levelOrder(tr);
for(int i=0; i<vec.size(); i++)
{
for(int j=0; j<vec[i].size(); j++)
{
cout<<vec[i][j]<<' ';
}
cout<<endl;
}
return 0;
}
运行结果
以上。
网友评论