#include<iostream>
#include<stack>
#include<vector>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
//二叉树节点结构
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int val):val(val),left(nullptr),right(nullptr){
};
};
void CreateBiTree(Tree *T)
{
TELemType
}
//前序遍历 递归法
void PreOrder( TreeNode *T)
{
if(T==NULL){return ;}
cout<<T->val<<endl;
PreOrder(T->left);
PreOrder(T->right);
}
//中序遍历 递归法
void middle( TreeNode *T)
{
if(T==NULL){return ;}
middle(T->left);
cout<<T->val<<endl;
middle(T->right);
}
//后序遍历 递归法
void PostOrder(TreeNode *T)
{
if(T==NULL){return ;
}
PostOrder(T->left);
PostOrder(T->right);
cout<<T->val<<endl;
}
class Solution
{
// 循环迭代前序遍历
public :
vector<int > preorderTraversal(TreeNode * root)
{
stack<TreeNode *> st;
vector<int> result;
if(root==NULL) return result;
st.push(root);//将根节点地址
while(!st.empty())
{
TreeNode * node=st.top();//获取当前节点的地址
result.push_back(node->val);//取该节点的值放入容器中
st.pop();//弹出当前节点地址
if(node->right) st.push(node->right);//若当前节点右孩子地址存在则压入到st
if(node->left) st.push(node->left);
}
return result;
}
//中序遍历二叉树 迭代法
vector<int> middlerun(TreeNode * root)
{
vector<int> result;
stack<TreeNode *> st;
TreeNode * cur=root;
while(cur!=NULL||!st.empty())
{
if(cur!=NULL)
{
st.push(cur);
cur=cur->left;
}
else
{
cur=st.top();
st.pop();
result.push_back(cur->val);
cur=cur->right;
}
}
return result;
}
//中序遍历二叉树
vector<int> middle2(TreeNode* root)
{
vector<int> result;
stack<TreeNode *> st;
if(root!=NULL) st.push(root);
while(!st.empty())
{
TreeNode *node=st.top();
if(node!=NULL)
{
st.pop();
if(node->right)st.push(node->right);
st.push(node);
st.push(NULL);
if(node->left)st.push(node->left);
}
else
{
st.pop();
node=st.top();
st.pop();
result.push_back(node->val);
}
}
return result;
}
};
int main()
{
TreeNode * T=(TreeNode *) malloc(10*sizeof(TreeNode)) ;
T->val=2;
TreeNode one(1);
TreeNode two(2);
TreeNode three(3);
TreeNode four(4);
TreeNode five(5);
one.left=&two;
one.right=&three;
two.left=&four;
two.right=&five;
cout<<four.left<<endl;
middle(&one) ;
cout<<endl;
PreOrder(&one);
cout<<endl;
Solution solve;
vector <int> res=solve.middle2(&one);
for(int i:res)
{
cout<<i<<endl;
}
cout<<endl;
middle(&one) ;
return 0;
}