A
B C
D E
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
typedef struct treenode {//二叉树的结构体
int val;
struct treenode* left;
struct treenode* right;
}Tree;
typedef struct node {//后续遍历添加指针
Tree* link;
bool first;
node() :link(NULL), first(true) {};
}Node;
Tree* create(int x) {//创建二叉树
Tree* t;
t = (Tree*)malloc(sizeof(Tree));
t->val = x;
t->right = t->left = nullptr;
return t;
}
void preorder(Tree* a) {//递归前序遍历
if (a == nullptr)
return;
cout<<a->val<<" ";
preorder(a->left);
preorder(a->right);
}
void preorder1(Tree* t) {//非递归前序遍历
stack<Tree*>s;
if (t == NULL)
return;
Tree* p = t;
while(p!=NULL||!s.empty()) {
while (p!=NULL) {
s.push(p);
cout << p->val<<" ";
p = p->left;
}
while (!s.empty()) {
p = s.top();
s.pop();
p = p->right;
}
}
}
void inorder(Tree* t) {//递归中序遍历
if (t == nullptr) {
return;
}
inorder(t->left);
cout << t->val<<" ";
inorder(t->right);
}
void postorder(Tree* t) {//递归后续遍历
if (t == nullptr)
return;
postorder(t->left);
postorder(t->right);
cout << t->val << " ";
}
void leveoorder(Tree* t) {//层次遍历
queue<Tree*>Q;
Tree* p = t;
Q.push(p);
while (!Q.empty()) {
p = Q.front();
cout << Q.front()->val<<" ";
Q.pop();
if (p->left) {
Q.push(p->left);
}
if (p->right)
Q.push(p->right);
}
}
void inorder1(Tree* t) {//非递归中序遍历
stack<Tree*>s;
Tree* p=t;
while (p != NULL || !s.empty()) {
while (p!=NULL) {
s.push(p);
p = p->left;
}
if (!s.empty()) {
p = s.top();
s.pop();
cout << p->val<<" ";
p = p->right;
}
}
}
void postorder1(Tree* root) {//非递归后续遍历
stack<Node*>s;
Node* p;
while (root || !s.empty()) {
if (root) {
p = new Node();
p->link = root;
s.push(p);
root = root->left;
}
else {
p = s.top();
s.pop();
if (p->first == true) {
s.push(p);
p->first = false;
root = p->link->right;
}
else {
cout << p->link->val << " ";
}
}
}
}
int sizeleafTrree(Tree* t) {//返回节点个数
if (t == nullptr)
return 0;
return 1 + sizeleafTrree(t->left) + sizeleafTrree(t->right);
}
int Treesize(Tree* t) {//返回叶子节点个数
if (t == nullptr)
return 0;
if (t->left == nullptr && t->right == nullptr)
return 1;
return Treesize(t->left) + Treesize(t->right);
}
int main() {
Tree* A= create(1);
Tree* B = create(2);
Tree* C = create(3);
Tree* D = create(4);
Tree* E= create(5);
//Tree* A = create(1);
A->left = B;
A->right = C;
B->left = D;
B->right = E;
preorder(A);
cout << endl;
inorder(A);
cout << endl;
postorder(A);
cout << endl;
leveoorder(A);
cout << endl;
inorder1(A);
cout << endl;
postorder1(A);
/*printf("\n");
cout << sizeleafTrree(A) << endl;
cout << Treesize(A) << endl;
preorder1(A);*/
return 0;
}