using namespace std;
struct BiNode{
int data;
BiNode *rchild,*lchild;
};
class BiSortTree{
public:
BiSortTree(int a[], int n){
root = NULL;
for(int i=0;i<n;i++){
BiNode *p = new BiNode;
p->lchild=p->rchild=NULL;
p->data = a[i];
InsertBST(root,p);
}
}
~BiSortTree(){}
void InsertBST(BiNode*&root, BiNode*s){
if(root==NULL){
root=s;
return;
}
if(root->data > s->data)
InsertBST(root->lchild, s);
else
InsertBST(root->rchild, s);
}
BiNode* getRoot(){
return root;
}
void InOrder(BiNode*root){
if(root){
InOrder(root->lchild);
cout<<root->data<<" ";
InOrder(root->rchild);
}
}
void Convert(BiNode*root, BiNode*&last){
if(root==NULL) return;
Convert(root->lchild, last);
root->lchild = last;
if(last!=NULL){
last->rchild = root;
}
last = root;
Convert(root->rchild, last);
}
BiNode* ConvertBiTreeToLink(){
if(root==NULL)
return NULL;
BiNode *last = NULL;
Convert(root, last);
//返回的节点为链表的最左端节点
while(root->lchild!=NULL){
root = root->lchild;
}
return root;
}
private:
BiNode *root;
};
int main()
{
int r[]={63,90,70,55,67,42,98};
BiSortTree m(r,7);
BiNode* lHead = m.ConvertBiTreeToLink();
while(lHead){
cout<<lHead->data<<" ";
lHead = lHead->rchild;
}
return 0;
}
二叉排序树转化为双向链表C++
最新推荐文章于 2020-10-17 19:30:07 发布