這是一道挺有趣的題,其解題的思路主要仍是二叉樹的中序遍歷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; }