给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
解题思路:在访问过程中,我们只需要将同一层中的节点同时入队列即可。在将该queue中所有元素出队列的同时,将下一层的元素进队列,完成交接。
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> res;
if (!root)
{
return res;
}
vector<int> vtmp;
queue<TreeNode *> qu;
TreeNode * cur;
int len = 1;
qu.push(root);
while (!qu.empty())
{
for (int i = 0; i < len; i++)
{
cur = qu.front();
vtmp.push_back(cur->val);
qu.pop();
if (cur->left)
{
qu.push(cur->left);
}
if (cur->right)
{
qu.push(cur->right);
}
}
res.push_back(vtmp);
vtmp.clear();
len = qu.size();
}
return res;
}
int main()
{
TreeNode * root = new TreeNode(3);
TreeNode * tmpl = new TreeNode(9);
root->left = tmpl;
TreeNode * tmpr = new TreeNode(20);
root->right = tmpr;
TreeNode * tmpll = new TreeNode(11);
tmpl->left = tmpll;
TreeNode * tmplr = new TreeNode(8);
tmpl->right = tmplr;
TreeNode * tmprl = new TreeNode(15);
tmpr->left = tmprl;
TreeNode * tmprr = new TreeNode(7);
tmpr->right = tmprr;
TreeNode * tmprrr = new TreeNode(2);
tmprr->right = tmprrr;
levelOrder(root);
system("pause");
return 0;
}