/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
vector<TreeNode*> curr, next;
curr.push(root);
while(!curr.empty()){ // this condition is actually whether we have elements in the next level
ans.push_back({});
for (TreeNode * node : curr){
ans.back().push_back(curr->val);
if (curr->left) next.push_back(curr->left);
if (curr->right) next.push_back(curr->right);
}
curr.swap(next);
next.clear();
}
return ans;
}
};
copied answer from Huahua Leetcode. Note this is BFS but they do not use a Queue. Instead, they use a "next" vector and check if it's empty.
Error:
- Misunderstood "curr" vs "node". Note here "curr" is the level, not the node anymore.
- Miss the edge case where root == empty.
Error:
- Misunderstood "curr" vs "node". Note here "curr" is the level, not the node anymore.
- Miss the edge case where root == empty.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.