比想象中的简单。。。日常记录
#include<iostream>
#include<stack>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void inorder(TreeNode* root)
{
stack<TreeNode*> st;
TreeNode* p = root;
while (p || !st.empty())
{
if (p)
{
st.push(p);
p = p->left;
}
else
{
p = st.top();
st.pop();
cout << p->val;
p = p->right;
}
}
}
void postorder(TreeNode* root)
{
stack<TreeNode*> st1, st2;
TreeNode* p;
st1.push(root);
while (!st1.empty())
{
p = st1.top();
st1.pop();
if (p->left != NULL)
{
st1.push(p->left);
}
if (p->right != NULL)
{
st1.push(p->right);
}
st2.push(p);
}
while (!st2.empty())
{
p = st2.top();
st2.pop();
cout << p->val;
}
return;
}
TreeNode* creat()
{
int temp;
cin >> temp;
if (temp == -1)
{
return NULL;
}
TreeNode* root = new TreeNode(temp);
root->left = creat();
root->right = creat();
return root;
}
int main()
{
TreeNode* root = creat();
inorder(root);
cout << endl;
postorder(root);
}