歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 二叉樹轉換為雙向環形鏈表

二叉樹轉換為雙向環形鏈表

日期:2017/3/1 9:36:58   编辑:Linux編程

二叉樹的節點與雙向環形鏈表的節點類似,均含有兩個指向不同方向的指針,因此他們之間的轉化是可以實現的。下面介紹一種遞歸的實現方法。由於方法比較簡單,就直接上代碼了

二叉樹的建立

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://www.linuxidc.com/Linux/2013-04/83661.htm

【遞歸】二叉樹的先序建立及遍歷 http://www.linuxidc.com/Linux/2012-12/75608.htm

在JAVA中實現的二叉樹結構 http://www.linuxidc.com/Linux/2008-12/17690.htm

【非遞歸】二叉樹的建立及遍歷 http://www.linuxidc.com/Linux/2012-12/75607.htm

二叉樹遞歸實現與二重指針 http://www.linuxidc.com/Linux/2013-07/87373.htm

二叉樹先序中序非遞歸算法 http://www.linuxidc.com/Linux/2014-06/102935.htm

輕松搞定面試中的二叉樹題目 http://www.linuxidc.com/linux/2014-07/104857.htm

Copyright © Linux教程網 All Rights Reserved