在 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