题目:
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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
层次遍历的规律是先遍历同一层的节点节点,然后再遍历以该层节点为根节点的所有左右子树,因此,我们可采用队列队列来进行存储,本层节点的左右子节点,以便下次遍历。由于本题要求一层一层的输出,所以需要设置以为标记为进行标记,以便分层输出。
代码:
/**
* Definition for a binary tree node.
**/
typedef struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}*BinaryTree;
class Solution {
public:
void CreateTree(BinaryTree &T)//创建二叉树,二叉树以先序遍历的顺序输入
{
char data;
cin >> data;
if (data == '#')
T = NULL;
else
{
T = new TreeNode(data - '0');
CreateTree(T->left);
CreateTree(T->right);
}
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> >ret;
vector<int > temp;
if (root == NULL)
return ret;
queue< TreeNode *> q;
TreeNode *p=root;
q.push(p);
q.push(NULL);//以NULL作为标记位
while (!q.empty())
{
p = q.front();
while (p != NULL)
{
q.pop();
temp.push_back(p->val);
if (p->left != NULL)
{
q.push(p->left);
}
if (p->right != NULL)
{
q.push(p->right);
}
p = q.front();
}
q.pop();
ret.push_back(temp);
temp.clear();
if (!q.empty())
{
q.push(NULL);
}
}
return ret;
}
};