码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-12 13:37:24      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:blog   http   os   io   2014   ar   代码   amp   

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

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

bubuko.com,布布扣\

代码:

#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;  
}  


平衡二叉树转化为双向链表,布布扣,bubuko.com

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

标签:blog   http   os   io   2014   ar   代码   amp   

原文地址:http://blog.csdn.net/buyingfei8888/article/details/38513305

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!