题目
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}”.
分析
给定一颗二叉树,返回其层序遍历序列。
要求按照二叉树的结构,分层存储节点元素。
既然要求分层返回遍历结果,我们知道,层序遍历是利用队列先进先出的结构特点,依次遍历。按照本题要求,在遍历过程中必须将每层涉及到的节点单独存储,才能保证得到独立层节点序列。
//定义两个队列,一个存储所有的父节点,另一个存储他们的子节点也就是子层
AC代码
/**
* Definition for a binary tree node.
* 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 vector<vector<int> >();
vector<vector<int> > ret;
//定义两个队列,一个存储所有的父节点
queue<TreeNode *> parents;
parents.push(root);
while (!parents.empty())
{
//存储当前层的遍历结果
vector<int> tmp;
//定义队列另一个存储他们的子节点也就是子层
queue<TreeNode *> childs;
while (!parents.empty())
{
TreeNode *node = parents.front();
tmp.push_back(node->val);
//弹出当前父节点
parents.pop();
if (node->left)
childs.push(node->left);
if (node->right)
childs.push(node->right);
}
//存储当前层的遍历结果
ret.push_back(tmp);
//遍历下一层
parents = childs;
}
return ret;
}
};