Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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