考试出现的算法题,好像网上没人遇到,贴一下希望能帮助到需要的人。
#include <iostream>
using namespace std;
typedef struct BTNODE
{
char data;
struct BTNODE *lchild,*rchild;
}BTNODE,*Btree;
/* 二叉树的三叉链表存储表示 */
typedef struct BiTPNode
{
char data;
struct BiTPNode *parent,*lchild,*rchild; /* 双亲、左右孩子指针 */
}BiTPNode,*BiPTree;
BiTPNode testNode;
void CreateBiTree(Btree &T) //可以换成给直接给出的二叉树
{
char ch;
cin>>ch;
if( ch == '#' )
{
T = NULL;
}
else
{
T = new BTNODE;
T->data = ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
void createBipTree(BTNODE *BT,BiPTree &T){ //就是将三叉链表的先序创建结合到先序遍历中,主体就是先序遍历代码
if(BT!= NULL){
T=new BiTPNode;
T->data=BT->data;
T->parent=NULL;
createBipTree(BT->lchild,T->lchild);
if(T->lchild){
T->lchild->parent=T;
}
createBipTree(BT->rchild,T->rchild);
if(T->rchild)
T->rchild->parent=T;
}else{
T = NULL;
}
}
void inorder(BTNODE *BT){ //中序遍历二叉链表
if(BT!= NULL){
inorder(BT->lchild);
cout<<BT->data<<" ";
inorder(BT->rchild);
}
}
void postorder(BTNODE *BT){ //后序遍历二叉链表
if(BT!= NULL){
postorder(BT->lchild);
postorder(BT->rchild);
cout<<BT->data<<" ";
}
}
void inorderBipTree(BiTPNode *BIP){ //中序遍历三叉链表
if(BIP!=NULL){
inorderBipTree(BIP->lchild);
cout<<BIP->data<<" ";
inorderBipTree(BIP->rchild);
}
}
int main()
{
Btree T;
BiPTree T2;
CreateBiTree(T); //这一步可以直接输入节点代替
createBipTree(T,T2);
inorder(T);
cout<<endl;
inorderBipTree(T2);
return 0;
}