用隊列實現(xiàn)樹的廣度優(yōu)先搜索
題目如下:
實現(xiàn)代碼如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
const vector<vector<int>> vvt;
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> vvt;
if(root == NULL) return vvt;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int size = q.size();
vector<int> level;
for(int i = 0; i < size; i++){
TreeNode* node = q.front();
level.push_back(node->val);
if( node->left != NULL ) q.push(node->left);
if( node->right != NULL ) q.push(node->right);
q.pop();
}
vvt.push_back(level);
}
reverse(vvt.begin(),vvt.end());
return vvt;
}
};
以前一直寫的深度優(yōu)先,感覺這個還是蠻新鮮的录淡,作為c++萌新,也學(xué)了一些c++中queue的函數(shù)
注:
queue中:pop()函數(shù)無返回值油坝,front()才有
vector<vector<int>> vvt類似于Java中的ArrayList嫉戚,
插入用push_back()
顛倒用reverse(vvt.begin(),vvt.end())