题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 81216
solution: #include <iostream> using namespace std; typedef struct BiNode { struct BiNode* lchild; struct BiNode* rchild; int data; }BiNode,*BiTree; class BiTreeToDList { private: BiNode* listHead; BiNode* pList; public: BiTreeToDList(); void createTree(BiTree & root); void inorder(BiTree root); void convert(BiNode* p); }; inline BiTreeToDList():listHead(NULL),pList(NULL) { } void BiTreeToDList::createTree(BiTree & root) { int data; cout<<"please input data:"<<endl; cin>>data; if('#'==data) return ; BiNode* node = new BiNode; root = node; try { node->data = data; node->lchild = NULL; node->rchild = NULL; throw "create node failer"; }catch(char* str) { cout<<str<<endl; exit(-1); } createTree(root->lchild); createTree(root->rchild); }; void BiTreeToDList::convert(BiNode* p) { p->lchild = pList; if(NULL!=pList) { pList->rchild = p; } else { listHead = p; } pList = p; }; void BiTreeToDList::inorder(BiTree root) { if(NULL==root) return ; inorder(root->lchild); convert(root); inorder(root->rchild); };
把二元查找树转变成排序的双向链表
最新推荐文章于 2019-08-05 19:30:18 发布