Created
July 20, 2019 17:51
-
-
Save zhangxiaomu01/341193c98ce20b5b8ec5198442bc8c16 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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