问题描述
笔记
关键点,是要建立队列来实现广度优先遍历,同时以NULL来标记每一层的结束,有点神奇啊。
代码
/**
* 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) {
// write your code here
vector<vector<int>> res;
res.clear();
if (root == NULL)
return res;
std::queue<TreeNode*> q;
q.push(root);
q.push(NULL);
vector<int> tmp;
tmp.clear();
while(!q.empty())
{
TreeNode *nowNode = q.front();
q.pop();
if (nowNode != NULL)
{
tmp.push_back(nowNode->val);
if (nowNode->left != NULL)
q.push(nowNode->left);
if (nowNode->right != NULL)
q.push(nowNode->right);
}
else
{
if (!tmp.empty())//KEY. if we dont write this, we will keep pushing NULL in the queue at the end of the traversal so that the while loop will never end.
{
res.push_back(tmp);
tmp.clear();
q.push(NULL);
// WHY? USE NULL TO SPLIT DIFFERENRT LEVEL.
//IF q.front == NULL means that this level is finished. and all next level is in the queue.
// so that we can put NULL into the queue.
}
}
}
return res;
}
};
二次练习
/**
* 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) {
// write your code here
vector<vector<int>> res;
if (root == NULL)
return res;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
vector<int> tmp;
while (!q.empty())
{
TreeNode* nowNode = q.front();
q.pop();
if (nowNode)
{
tmp.push_back(nowNode->val);
if (nowNode->left)
q.push(nowNode->left);
if (nowNode->right)
q.push(nowNode->right);
}
else// 遇到一个NULL,说明遍历完了一层
{
if (!tmp.empty())// 注意加入这个判断来防止一直往空队列中插入NULL,导致死循环
{
res.push_back(tmp);
tmp.clear();
q.push(NULL);// 既然遍历完了一层,那就在队列中再插入一个NULL来标记当前这一层的结束。
}
}
}
}
};