对于树的层次遍历,用STL queue来实现,我以前的方法一直是用一个level来判断是否到了新的一层;而这种方法直接能获知当前层的节点数,很好的方法,学习了。
这种方法也适用于任意的BFS.
/**
* 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> > levelOrderBottom(TreeNode *root) {
vector<vector<int> > res;
if(root == NULL) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int levelSize = q.size();
vector<int> row;
for(int i = 0; i < levelSize; i ++){
TreeNode *cur = q.front(); q.pop();
row.push_back(cur->val);
if(cur->left != NULL) q.push(cur->left);
if(cur->right != NULL) q.push(cur->right);
}
res.push_back(row);
}
reverse(res.begin(), res.end());
return res;
}
};