题目描述:
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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
二叉树的层序遍历,但是和往常不一样的是需要对每一层都有一个向量储存,应该要考虑到节点深度的问题,所以用pair将节点和深度组合起来,这样每次遍历都记录节点的深度,然后在最后的处理时,把节点按照深度放进各个向量中。注意层序遍历是由队列实现的,它能保证下一层的节点遍历的顺序必定在前一层节点之后,恰好满足层序遍历的要求。
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode* root)
{
queue<pair<TreeNode*,int> > q;
vector<pair<int,int> > v;
if(root==NULL)
{
vector<vector<int> > result;
return result;
}
else if(root!=NULL)
{
pair<TreeNode*,int> p;
p.first=root;
p.second=0;
q.push(p);
while(!q.empty())
{
p=q.front();
pair<int,int> x;
x.first=p.first->val;
x.second=p.second;
v.push_back(x);
q.pop();
if(p.first->left!=NULL)
{
pair<TreeNode*,int> l;
l.first=p.first->left;
l.second=p.second+1;
q.push(l);
}
if(p.first->right!=NULL)
{
pair<TreeNode*,int> r;
r.first=p.first->right;
r.second=p.second+1;
q.push(r);
}
}
}
int n=v.size();
int m=v[n-1].second;
vector<vector<int> > result(m+1);
for(int i=0;i<n;i++)
{
result[v[i].second].push_back(v[i].first);
}
return result;
}
};