#include <iostream> #include <cstdlib> #include<queue> #include <stack> using namespace std; //二叉树链表的存储结构 typedef struct BiTNode { int data;//节点数据 struct BiTNode *lchild, *rchild;//左右孩子指针 }BiTNode, *BiTree; //二叉树的建立 void CreatBiTree(BiTree &T) { int ch; cin >> ch; if (ch == 0) T = NULL; else { T = new BiTNode;//生成根节点 if (!T) exit(1); T->data = ch; CreatBiTree(T->lchild); //构造左子树 CreatBiTree(T->rchild); //构造右子树 } } //创建二叉树 BiTNode* create(int b[], int n) { BiTNode* ptree =new BiTNode [n]; int i; for (i = 0; i < n; i++) { ptree[i].data = b[i];//给每个节点赋值 ptree[i].lchild = NULL;// ptree[i].rchild = NULL; } for (i = 0; 2*i+1<n; i++)//原来的父亲节点范围为[1,n/2],所以要取到n/2 { ptree[i].lchild = &ptree[2 * i + 1];//把第2*i+1个结点的地址赋给左孩子 ptree[i].rchild = &ptree[2 * i + 2];//把第2*i+2个结点的地址赋给右孩子 } return ptree; } //前序遍历 void PreOrderTraverse(BiTNode* T) { if (!T) return; cout << T->data<<" ";//显示节点数据 PreOrderTraverse(T->lchild); PreOrderTraverse(T->rchild); } //中序遍历 void InOrderTraverse(BiTree T) { if (!T) return; InOrderTraverse(T->lchild); cout << T->data << " "; //显示节点数据 InOrderTraverse(T->rchild); } //后序遍历 void PostOrderTraverse(BiTree T) { if (!T) return; PostOrderTraverse(T->lchild); PostOrderTraverse(T->rchild); cout << T->data << " "; //显示节点数据 } void Levelorder(BiTNode *T)//层析遍历 { if (!T) return; BiTNode *temp; queue<BiTNode*>q; q.push(T); while (!q.empty()) { temp = q.front(); cout << temp->data << " "; if (temp->lchild) q.push(temp->lchild); if (temp->rchild) q.push(temp->rchild); q.pop(); } } int main() { BiTNode *T=NULL; BiTNode *T1; int a[7] = { 1,2,3,4,5,6,7}; int n = size(a); T1=create(a, n); cout << "前序排序:"; Levelorder(T1);//层析遍历 cout << endl; cout << "前序排序:"; PreOrderTraverse(T1); //前序排序 cout << endl; cout << "中序排序:"; InOrderTraverse(T1); //中序排序 cout << endl; cout << "后序排序:"; PostOrderTraverse(T1); //后序排序 cout << endl; return 0; }