Skip to content

Instantly share code, notes, and snippets.

@qiaoxu123
Created March 5, 2019 01:21
Show Gist options
  • Save qiaoxu123/9f08eed03cf7778e59e17b3fa5c31250 to your computer and use it in GitHub Desktop.
Save qiaoxu123/9f08eed03cf7778e59e17b3fa5c31250 to your computer and use it in GitHub Desktop.
> 考察二叉树的宽度遍历算法,在这使用了queue来实现
//Runtime: 8 ms, faster than 100.00%
//Memory Usage: 13.9 MB, less than 55.99%
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
if(!root) return result;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
vector<int> cur_vec;
while(!q.empty()){
TreeNode* t = q.front();
q.pop();
if(t == NULL){
result.push_back(cur_vec);
cur_vec.resize(0);
if(q.size() > 0)
q.push(NULL);
}else {
cur_vec.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment