二叉排序树转化为双向链表

#include<iostream>
using namespace std;

struct BTnode{
int value;
BTnode *left;
BTnode *right;

}*head=NULL,*tail=NULL;

BTnode *newNode(int value){//初始化一个新的节点
BTnode *Node=(BTnode *)malloc(sizeof(BTnode));
Node->left=NULL;
Node->right=NULL;
Node->value=value;
return Node;
}
BTnode *constructBT(){//构造一颗二叉排序树
BTnode *root=newNode(10);
root->left=newNode(6);
root->right=newNode(14);
root->left->left=newNode(4);
root->left->right=newNode(8);
root->right->left=newNode(12);
root->right->right=newNode(16);
return root;
}
void Btree2DoubleList(BTnode *curr){
if(!tail){
head=tail=curr;//第一次访问的是最小节点,一开始head,tail指针均指向它
}
else{  //从第二个节点之后,将当前节点的左指针指向链表尾,链表尾节点右指针指向当前节点,最后链表尾节点指向当前节点
curr->left=tail;
tail->right=curr;
tail=curr;
}
}
void transBtree2DoubleList(BTnode *curr){//中序遍历二叉排序树,第一次访问的是最小节点。。。
if(curr==NULL)
return;
if(curr->left)
transBtree2DoubleList(curr->left);
Btree2DoubleList(curr);
if(curr->right)
transBtree2DoubleList(curr->right);
}
int main(){
BTnode *root=constructBT();
transBtree2DoubleList(root);
while(head)
{
cout<<head->value<<" ";
head=head->right;
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值