Reputation: 423
I was doing some LeetCode questions (new at LeetCode) and I wrote a solution for traversing a binary tree iteratively. I used a stack, and I believe my logic works, but LeetCode is giving me a run time error. How can I fix this?
Here is my code:
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
TreeNode* temp = root;
vector<int> v;
stack<TreeNode*> s;
if (temp == NULL)
return v;
while (true){
while (temp != NULL){
if (temp->right)
s.push(temp->right);
s.push(temp);
temp = temp->left;
}
if (s.empty())
break;
temp = s.top();
s.pop();
if (s.top() == temp->right){
s.pop();
s.push(temp);
temp = temp->right;
}else{
v.push_back(temp->val);
temp = NULL;
}
}
return v;
}
};
Please help, thanks!
Upvotes: 1
Views: 87
Reputation: 1278
Corrected code: Additional check in if is to add a check on empty of stack
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
class TreeNode{public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(){
left=right=NULL;
}
TreeNode(int data){
val=data;
}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root)
{
TreeNode* temp = root;
vector<int> v;
stack<TreeNode*> s;
if (temp == NULL)
return v;
while (true){
while (temp != NULL){
if (temp->right)
s.push(temp->right);
s.push(temp);
temp = temp->left;
}
if (s.empty())
break;
temp = s.top();
s.pop();
if (!s.empty() && s.top() == temp->right) {
s.pop();
s.push(temp);
temp = temp->right;
}else{
v.push_back(temp->val);
temp = NULL;
}
}
return v;
}
};
int main(){
TreeNode* root = NULL;
root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
Solution obj;
vector<int >v;
v =obj.postorderTraversal(root);
for(auto i=v.begin();i!=v.end();++i)
cout<<*i;
}
Output: 4526731
Upvotes: 1
Reputation: 56865
Your code is crashing here when you only have one item left in the stack:
temp = s.top(); // remove the last item from the stack
s.pop(); // empty the stack
if (s.top() == temp->right){ // attempt to access the top of the stack.. boom!
The fix is to test for an empty stack before checking top
:
if (!s.empty() && s.top() == temp->right) {
Upvotes: 1