-
后序遍历二叉树(非递归实现)
题目来源 -
C++代码实现
class Solution
{
public:
vector<int> postorderTraversal(TreeNode* root)
{
vector<int> result;
stack<TreeNode*> datastack1;
stack<TreeNode*> datastack2;
if (root != NULL)
{
datastack1.push(root);
while (!datastack1.empty())
{
root = datastack1.top();
datastack2.push(root);
datastack1.pop();
if (root->left != NULL)
{
datastack1.push(root->left);
}
if (root->right != NULL)
{
datastack1.push(root->right);
}
}
}
int length = datastack2.size();
for (int i = 0; i < length; i++)
{
result.push_back((datastack2.top())->val);
datastack2.pop();
}
return result;
}
};
将最后的datastack2
向result
中倒数据改为如下代码也可:
while(!datastack2.empty())
{
result.push_back( (datastack2.top() )->val);
datastack2.pop();
}
- 第一次出现BUG:
/**
* 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<int> postorderTraversal(TreeNode* root)
{
vector<int> result;
stack<TreeNode*> datastack1;
stack<TreeNode*> datastack2;
if(root != NULL)
{
datastack1.push(root);
while(!datastack1.empty())
{
root = datastack1.top();
datastack2.push(root);
datastack1.pop();
if(root->left != NULL)
{
datastack1.push(root->left);
}
if(root->right != NULL)
{
datastack1.push(root->right);
}
}
}
for(int i = 0;i < datastack2.size();i++)
{
result.push_back( (datastack2.top() )->val);
datastack2.pop();
}
return result;
}
};
最后发现BUG出现在
for(int i = 0;i < datastack2.size();i++)
{
result.push_back( (datastack2.top() )->val);
datastack2.pop();
}
datastack2
每pop出一次数据,datastack2.size()
就会减一,同时i++
,导致过早的结束了这个循环,正确的写法如下:
int length = datastack2.size();
for (int i = 0; i < length; i++)
{
result.push_back((datastack2.top())->val);
datastack2.pop();
}