Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created July 20, 2019 17:51
Show Gist options
  • Save zhangxiaomu01/341193c98ce20b5b8ec5198442bc8c16 to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/341193c98ce20b5b8ec5198442bc8c16 to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
//We can use the length of the tree to indicate the elements in this level
//A common trick, remember
queue<TreeNode*> Q;
Q.push(root);
while(!Q.empty()){
int len = Q.size();
vector<int> tempStack;
for(int i = 0; i < len; i++){
TreeNode* cur = Q.front();
Q.pop();
tempStack.push_back(cur->val);
if(cur->left) Q.push(cur->left);
if(cur->right) Q.push(cur->right);
}
res.push_back(tempStack);
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment