在 C++ 中将二叉树转换为循环双向链表
在本教程中,我们将讨论一个二叉树转换为循环双向链表的程序。
为此,我们将使用一棵二叉树。我们的任务是将左和右结点分别转换为左和右元素。并取得二叉树的中序来作为循环链表的序列顺序
示例
#include<iostream>
using namespace std;
//node structure of the binary tree
struct Node{
struct Node *left, *right;
int data;
};
//appending rightlist to the end of leftlist
Node *concatenate(Node *leftList, Node *rightList){
//if one list is empty return the other list
if (leftList == NULL)
return rightList;
if (rightList == NULL)
return leftList;
Node *leftLast = leftList->left;
Node *rightLast = rightList->left;
//connecting leftlist to rightlist
leftLast->right = rightList;
rightList->left = leftLast;
leftList->left = rightLast;
rightLast->right = leftList;
return leftList;
}
//converting to circular linked list and returning the head
Node *bTreeToCList(Node *root){
if (root == NULL)
return NULL;
Node *left = bTreeToCList(root->left);
Node *right = bTreeToCList(root->right);
root->left = root->right = root;
return concatenate(concatenate(left, root), right);
}
//displaying circular linked list
void print_Clist(Node *head){
cout << "Circular Linked List is :\n";
Node *itr = head;
do{
cout << itr->data <<" ";
itr = itr->right;
}
while (head!=itr);
cout << "\n";
}
//creating new node and returning address
Node *newNode(int data){
Node *temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
int main(){
Node *root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
Node *head = bTreeToCList(root);
print_Clist(head);
return 0;
}输出
Circular Linked List is : 25 12 30 10 36 15
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP