平衡二叉树转化为双向链表

 很容易想到递归,实现确实不是太容易,对本人来说。

平衡二叉树是有序的,要求链表也是有序。

\

代码:

#include<iostream>  
//平衡二叉树转化为双向链表
using namespace std;

typedef struct tree{
	int data;
	struct tree *lchild;
	struct tree *rchild;
}Tree,*pTree;

void createBST(pTree &pHead){
	int temp;
	scanf("%d",&temp);
	if(temp){
		pHead = new Tree();
		pHead->data = temp;
		createBST(pHead->lchild);
		createBST(pHead->rchild);
	}else{
		pHead = NULL;a
		return ;
	}
}

void print(pTree p){
	if(p){
		print(p->lchild);
		cout<<p->data<<" ";
		print(p->rchild);
	}else{
	  return ;
	}
}

void convertList(pTree root,pTree * pLastNode){
	if(root == NULL)
		return ;
	pTree cur = root;

	if(cur->lchild != NULL){
		convertList(root->lchild,pLastNode);
	}
	cur->lchild = *pLastNode;
	if(*pLastNode != NULL){
		(*pLastNode)->rchild = cur;
	}
	*pLastNode = cur;
	if(cur->rchild != NULL){
		convertList(cur->rchild,pLastNode);
	}
}

void printList(const pTree cur1){
	pTree	cur = cur1;
	while(cur){
		cout<<cur->data<<" ";
		cur = cur->rchild;
	}
}

pTree convert(pTree root){
	if(NULL == root)
		return root;
	pTree  pLastNode = NULL;
	convertList(root,& pLastNode);

	pTree pHead = pLastNode;
	while(pHead != NULL && pHead ->lchild != NULL){
		pHead = pHead->lchild;
	}
	return pHead;
}


int main()  
{  
	pTree pHead = NULL;
	createBST(pHead);
	cout<<"原平衡二叉树的中序遍历:";
	print(pHead);
	cout<<endl;
	cout<<"链表的从左到右序列:";
	pTree pHead1=	convert(pHead);
	printList(pHead1);
    return 0;  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值