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

二叉树转换为双向环形链表

时间:2014-11-25 16:33:53      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:二叉树   链表   递归   

二叉树的节点与双向环形链表的节点类似,均含有两个指向不同方向的指针,因此他们之间的转化是可以实现的。下面介绍一种递归的实现方法。由于方法比较简单,就直接上代码了

二叉树的建立

node* create(const string& s)
{
	node* res = new node;
	res->left = nullptr;
	res->right = nullptr;
	res->s = s;
	return res;
}
node* insert(node* root, const string& s)
{
	if(root == nullptr)
	{
		root = create(s);
		return root;
	}
	node* temp = root;
	while(temp!=nullptr)
	{
		if(temp->s > s)
		{
			if(temp->left == nullptr)
			{
				temp->left = create(s);
				return root;
			}
			else
				temp = temp->left;
		}
		else
		{
			if(temp->right == nullptr)
			{
				temp->right = create(s);
				return root;
			}
			temp = temp->right;
		}
	}
}
二叉树转换为链表

node* join_two_cycle(node* first, node* second)
{
	if(first == nullptr)
		return second;
	if(second == nullptr)
		return first;
	node* rail_first = first->left;
	node* rail_second = second->left;
	rail_first->right = second;
	second->left = rail_first;
	rail_second->right = first;
	first->left = rail_second;
	return first;
}
node* merge_to_list(node* x)
{
	if(x == nullptr)
		return nullptr;
	node* head_left = merge_to_list(x->left);
	node* head_right = merge_to_list(x->right);
	x->left = x;
	x->right = x;
	head_left = join_two_cycle(head_left,x);
	head_left = join_two_cycle(head_left,head_right);
	return head_left;
}
测试代码

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct node
{
	string s;
	node* left;
	node* right;
};
node* insert(node* root, const string& s);
node* merge_to_list(node* x);
void main()
{
	ifstream in("data.txt");
	if(!in.good())
	{
		cout<<"Error"<<endl;
		exit(0);
	}
	node* root = nullptr;
	while(!in.eof())
	{
		string s;
		in>>s;
		root = insert(root,s);
	}
	node* head;
	head = merge_to_list(root);
	node* end = head->left;
	node* temp = head;
	while(temp != end)
	{
		cout<<temp->s<<" ";
		temp = temp->right;
	}
	cout<<end->s<<endl;
}




二叉树转换为双向环形链表

标签:二叉树   链表   递归   

原文地址:http://blog.csdn.net/shaya118/article/details/41482235

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