您的位置:首页 > 其它

牛客网算法学习记录-按层遍历树

2016-05-17 23:09 399 查看
今天写了一题,学习了c++
题目:

有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。

给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。

思路:用两个队列进行存储,第一个队列先存储root,然后对第一个队列遍历之后,将它各个节点的孩子存放到第二个队列,再遍历第二个队列,将其孩子存放到第一个队列中,如此循环。

由于前期学习的时候课程给予的提示就是实用队列进行,所以选择了队列,但是对c++语言不熟悉,写了一个用队列的方法报错:

编译错误:您提交的代码无法完成编译

In file included from 第2行:

./solution.h:24:31: error: cannot cast from type 'void' to pointer type 'TreeNode *'

TreeNode *t = (TreeNode*)(q1.pop());

代码:

/*

struct TreeNode {

int val;

struct TreeNode *left;

struct TreeNode *right;

TreeNode(int x) :

val(x), left(NULL), right(NULL) {

}

};*/

class TreePrinter {

public:

vector<vector<int> > printTree(TreeNode* root) {

// write code here

vector<vector<int>> result;

int last = 0,nlast = 0;

queue<TreeNode*> q1;

queue<TreeNode*> q2;

q1.push(root);

while(!q1.empty()||!q2.empty()){

vector<int> v1;

vector<int> v2;

while(!q1.empty()){

TreeNode *t = (TreeNode*)(q1.pop());

if(t->left != NULL ){

q2.push(t->left);

}

if(t->right!=NULL ){

q2.push(t->right);

}

v1.push_back(t->val);

}

while(!q2.empty()){

TreeNode *t = (TreeNode*)(q2.pop());

if(t->left!=NULL ){

q2.push(t->left);

}

if(t->right!=NULL ){

q2.push(t->right);

}

v2.push_back(t->val);

}

if(v1.size()>0){

result.push_back(v1);

}

if(v2.size()>0){

result.push_back(v2);

}

}

return result;

}

};

未解决:队列的类型为queue<TreeNode*>,但没想通为什么pop出来的类型为void 而不是void*。也没查到什么资料,可能是太基础了。

解决:pop()操作只是元素退出队列操作,本身函数的返回值为void,所以如果需要取队列元素,使用front(),然后用pop()退出队列

所以打算改成比较大的数组,形成一个队列,并且做标记last,nlast。

修改后的代码:

/*

struct TreeNode {

int val;

struct TreeNode *left;

struct TreeNode *right;

TreeNode(int x) :

val(x), left(NULL), right(NULL) {

}

};*/

class TreePrinter {

public:

vector<vector<int> > printTree(TreeNode* root) {

// write code here

vector<vector<int>> result;

int last = 0,nlast = 0;

queue<TreeNode*> q1;

queue<TreeNode*> q2;

q1.push(root);

while(!q1.empty()||!q2.empty()){

vector<int> v1;

vector<int> v2;

while(!q1.empty()){

TreeNode *t = (q1.front());

q1.pop();

if(t->left != NULL ){

q2.push(t->left);

}

if(t->right!=NULL ){

q2.push(t->right);

}

v1.push_back(t->val);

}

while(!q2.empty()){

TreeNode *t = (q2.front());

q2.pop();

if(t->left!=NULL ){

q1.push(t->left);

}

if(t->right!=NULL ){

q1.push(t->right);

}

v2.push_back(t->val);

}

if(v1.size()>0){

result.push_back(v1);

}

if(v2.size()>0){

result.push_back(v2);

}

}

return result;

}

};

通过所有样例~

参考答案:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: