145. Binary Tree Postorder Traversal
Posted manual-linux
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了145. Binary Tree Postorder Traversal相关的知识,希望对你有一定的参考价值。
后序遍历二叉树(非递归实现)
题目来源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();
}
以上是关于145. Binary Tree Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 145. Binary Tree Postorder Traversal
145. Binary Tree Postorder Traversal
LeetCode145. Binary Tree Postorder Traversal 解题报告
145. Binary Tree Postorder Traversal