原题:
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}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
思路:利用广度优先搜索和队列数据结构。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
if(!root) return;
queue<TreeNode *> tmp;
vector<vector<int>> res;
vector<int> level;
tmp.push(root);
while(!tmp.empty()){
TreeNode *p = tmp.front();
tmp.pop();
level.push_back(p);
if(){
res.push_back(level);
level.clear();
}
if(!p->left) tmp.push(p->left);
if(!p->right) tmp.push(p->right);
}
return res;
}
};
如上图所示,如果我采用广度遍历的方式,我们并不容易找到每一层的分界。
========================================================================================================================
网上参考别人的代码后发现他们也是用的广度遍历!-。-我之所以无法确定边界是因为我把每一层的数据都推到了同一个队列里。而其它人使用了两个队列!【真是被自己蠢死了>///<】
所以我修改后的代码如下:
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
queue<TreeNode *> cur,next;
vector<vector<int>> res;
vector<int> level;
if(!root) return res;
cur.push(root);
while(!cur.empty()){
TreeNode *p = cur.front();
cur.pop();
level.push_back(p->val);
if(!p->left) next.push(p->left);
if(!p->right) next.push(p->right);
if(cur.empty()){
res.push_back(level);
level.clear();
cur = next;
while(!next.empty()){
next.pop();
}
}
}
return res;
}
};
按逻辑笔算了一遍,没有错误吧- 。-
==========================================================================================================================
把if(!p->left) next.push(p->left); if(!p->right) next.push(p->right);改为if(p->left) next.push(p->left); if(p->right) next.push(p->right);
真的是好弱智的错误啊 -皿-#AC了