手机版
你好,游客 登录 注册
背景:
阅读新闻

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

[日期:2014-11-25] 来源:Linux社区  作者:Lone_Dai [字体:大 中 小]

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

二叉树的建立

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

本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-11/109817.htm

linux
相关资讯       二叉树 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款