leetcode-102. hierarchical binary tree traversal
Modify the error code before
class Solution {
public:vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> LL;
queue<TreeNode*> RR;
int lev=0;
if(root) LL.push(root);
while(!LL.empty()||!RR.empty()){
if(!LL.empty()){
while(!LL.empty()){
TreeNode* tmp=LL.front();
LL.pop();
res[lev].push_back(tmp->val);
if(tmp->left) RR.push(tmp->left);
if(tmp->right) RR.push(tmp->right);
}
lev++;
}
else if(!RR.empty()){
while(!RR.empty()){
TreeNode* tmp=RR.front();
RR.pop();
res[lev].push_back(tmp->val);
if(tmp->left) LL.push(tmp->left);
if(tmp->right) LL.push(tmp->right);
}
lev++;
}
}
return res;
}
};
Thought problem solving: traversing each with a single queue, the lower left and right subtrees to another queue.
Cause: irregular array using the vector, RES is the vector <vector <>> type, where the outer layer is not inserted in the vector, the inner layer can not be used. See below:
if(){
while(){
```
res[lev].push_back(tmp->val);
```
}
lev++;
}
Amended as follows: first through the results stored in a temporary vector variables, the last save. See below:
if(){
vector<int> r;
while(){
```
r.push_back(tmp->val);
```
}
res.push_back(r);
}
AC modified the code:
/** * 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>> res;
queue<TreeNode*> LL;
queue<TreeNode*> RR;
if(root) LL.push(root);
while(!LL.empty()||!RR.empty()){
if(!LL.empty()){
vector<int> r;
while(!LL.empty()){
TreeNode* tmp=LL.front();
LL.pop();
r.push_back(tmp->val);
if(tmp->left) RR.push(tmp->left);
if(tmp->right) RR.push(tmp->right);
}
res.push_back(r);
}
else if(!RR.empty()){
vector<int> r;
while(!RR.empty()){
TreeNode* tmp=RR.front();
RR.pop();
r.push_back(tmp->val);
if(tmp->left) LL.push(tmp->left);
if(tmp->right) LL.push(tmp->right);
}
res.push_back(r);
}
}
return res;
}
};
Browse other blog, mentioned more problems (recommended check):
1. For empty Input [] can not be solved.
2.vector array initialization error, the code out of range.