描述:
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]
]
方法:
做了这么多层次遍历的变形了,终于做到原原本本的层次遍历了。写一下层次遍历的方法吧。使用queue数据结构;设立last指针,始终指向这一层的最后一个节点;设立nlast指针,始终记录最新进入队列的指针。这样每当遍历到last节点时,nlast就指向下一层最后的一个节点。循环终止的条件时队列中没有元素了。
C++代码:
/**
* Definition for binary tree
* 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) {
vector<vector<int> > res;
if(!root)
return res;
vector<int> store;
queue<TreeNode*> qu;
qu.push(root);
TreeNode* last = root;
TreeNode* nlast;
while(qu.size())
{
TreeNode* tmp = qu.front();
qu.pop();
store.push_back(tmp->val);
if(tmp->left)
{
nlast = tmp->left;
qu.push(tmp->left);
}
if(tmp->right)
{
nlast = tmp->right;
qu.push(tmp->right);
}
if(tmp == last)
{
last = nlast;
res.push_back(store);
store.clear();
}
}
return res;
}
};