#include <iostream>#include <string.h>usingnamespace Std;struct Node{NodeThe *left;//corresponds to a prev pointer to a doubly linked list.NodeThe *right;//corresponds to the next pointer to the doubly linked list. Char data; Node(Char d = char ()): Data(d), left(null), right(null){} };class MTree{public:MTree(): Root(NULL){} voidCreate_tree(Char *VLR,Char *LVR){int n = strlen(LVR);Create_tree(root,VLR,LVR,n); } voidCreate_tree(Node *&t,Char *VLR,Char *LVR,int n){//Construct two fork tree. If(n==0)return; int i = 0; While(VLR[0]!=LVR[i])i++; t = newNode(VLR[0]);Create_tree(t-left,VLR+1,LVR,i);Create_tree(t-right,VLR+i+1,LVR+i+1,n-i-1 ); } voidcreate_dlist(MTree &mt){Node*PR =NULL;create_dlist(root,PR,Mt. ) Root); } static voidPrintf(MTree &mt){//bidirectional linked list printing.Node*p = Mt.root; While(p! =NULL){cout<<p->data<< ""; p=p->right; }} private:voidcreate_dlist( node *t,node *&PR,node *&mt){//Constructs a doubly linked list. If(t= =NULL){return; }create_dlist(t-left,PR,mt); If(t! =NULL){t->left=pr; If(PR)Pr->right = t; If(pr= =NULL)mt=t; } if(PR! =null && PR, right = =null){pr->right=t; T->left = PR; } PR = t;create_dlist(t-right,PR,mt); } Private:Node*root;}; int main(){CharVLR[]="ABCDEFG"; CharLVR[]="Cbdafeg";MTreeMt Mt.Create_tree(VLR,LVR);MTreeMtlist; Mt.create_dlist(mtlist);MTree::Printf(mtlist); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm problem: Using binary tree to construct doubly linked list