这是一道挺有趣的题,其解题的思路主要仍是二叉树的中序遍历ios
先建立一个头结点List,而后经过中序遍历二叉树,把结点串起来便可!spa
注意点:指针
一、须要有一个指针来指向上一个已遍历过的结点code
二、若是不建立头结点,在后面遍历判断时比较麻烦blog
#include<iostream> using namespace std; struct Node{ int val; Node *lchild; Node *rchild; }; //建立二叉树 Node *CreateTree(){ char lflag='n',rflag='n'; Node*root=new Node; root->lchild=NULL; root->rchild=NULL; cout<<"请输入结点的值:"<<endl; cin>>root->val; cout<<"该结点是否有左子树?请输入Y or N:"; cin>>lflag; if(lflag=='y'||lflag=='Y')root->lchild=CreateTree(); else root->lchild =NULL; cout<<"该结点是否有右子树?请输入Y or N:"; cin>>rflag; if(rflag=='y'||rflag=='Y')root->rchild=CreateTree(); else root->rchild =NULL; return root; } //先序遍历二叉树 void ShowTreeXian(Node*root) { if(root!=NULL)cout<<root->val<<" "; if(root->lchild !=NULL)ShowTreeXian(root->lchild ); if(root->rchild !=NULL)ShowTreeXian(root->rchild ); } //p,为上一个已遍历过的结点,初始化为空头结点,二叉树转双向链表 void TreeToList(Node *root,Node *&p){ if(root->lchild !=NULL)TreeToList(root->lchild,p); root->lchild =p; p->rchild =root; p=root; if(root->rchild !=NULL)TreeToList(root->rchild,p); } //双向链表的遍历 void ShowList(Node *root) { cout<<"从左到右:"<<endl; while(root->rchild !=NULL){ cout<<root->rchild ->val<<" "; root=root->rchild ; } cout<<"从右到左:"<<endl; while(root->lchild!=NULL){ cout<<root->val<<" "; root=root->lchild ; } } int main(){ cout<<"建立二叉树:"<<endl; Node*root=CreateTree(); cout<<"先序遍历二叉树:"<<endl; ShowTreeXian(root); cout<<"二叉树转双向链表"<<endl; Node *List=new Node; List->lchild=NULL; List->rchild =NULL; List->val =0; Node *p=List; TreeToList(root,p); cout<<"双向链表的遍历"<<endl; ShowList(List); system("pause"); return 0; }