#include<vector>
#include<iostream>
#include<stack>
using namespace std;
struct TreeNode
{
int value;
TreeNode *left;
TreeNode *right;
};
vector<int> preOrder(TreeNode *root)
{
stack<TreeNode*> s;
vector<int> result;
TreeNode* p;
if(root!=nullptr)
s.push(root);
while(!s.empty())
{
p=s.top();
s.pop();
result.push_back(p->value);
if(p->right!=nullptr)
s.push(p->left);
if(p->left!=nullptr)
s.push(p->right);
}
return result;
}
vector<int> inOrder(TreeNode* root)
{
stack<TreeNode *>s;
TreeNode *p=root;
vector<int> result;
while(!s.empty()||p!=nullptr)
{
if(p!=nullptr)
{
s.push(p);
p=p->left;
}
else
{
p=s.top();
s.pop();
result.push_back(p->value);
p=p->right;
}
}
return result;
}
vector<int> postOrder(TreeNode* root)
{
vector<int>result;
TreeNode* pre=nullptr;
TreeNode* cur;
stack<TreeNode*>s;
if(root!=nullptr)
s.push(root);
while(!s.empty())
{
cur=s.top();
if(cur->left==nullptr&&cur->right==nullptr||(pre!=nullptr&&(pre==cur->left||pre==cur->right)))
{
result.push_back(cur->value);
s.pop();
pre=cur;
}
else
{
if(cur->right!=nullptr)
s.push(cur->right);
if(cur->left!=nullptr)
s.push(cur->left);
}
}
return result;
}
#include<iostream>
#include<stack>
using namespace std;
struct TreeNode
{
int value;
TreeNode *left;
TreeNode *right;
};
vector<int> preOrder(TreeNode *root)
{
stack<TreeNode*> s;
vector<int> result;
TreeNode* p;
if(root!=nullptr)
s.push(root);
while(!s.empty())
{
p=s.top();
s.pop();
result.push_back(p->value);
if(p->right!=nullptr)
s.push(p->left);
if(p->left!=nullptr)
s.push(p->right);
}
return result;
}
vector<int> inOrder(TreeNode* root)
{
stack<TreeNode *>s;
TreeNode *p=root;
vector<int> result;
while(!s.empty()||p!=nullptr)
{
if(p!=nullptr)
{
s.push(p);
p=p->left;
}
else
{
p=s.top();
s.pop();
result.push_back(p->value);
p=p->right;
}
}
return result;
}
vector<int> postOrder(TreeNode* root)
{
vector<int>result;
TreeNode* pre=nullptr;
TreeNode* cur;
stack<TreeNode*>s;
if(root!=nullptr)
s.push(root);
while(!s.empty())
{
cur=s.top();
if(cur->left==nullptr&&cur->right==nullptr||(pre!=nullptr&&(pre==cur->left||pre==cur->right)))
{
result.push_back(cur->value);
s.pop();
pre=cur;
}
else
{
if(cur->right!=nullptr)
s.push(cur->right);
if(cur->left!=nullptr)
s.push(cur->left);
}
}
return result;
}