二叉排序树转换为有序的双向链表c语言
时间: 2023-04-25 19:06:04 浏览: 196
排序树 变成双向链表
二叉排序树转换为有序的双向链表的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 定义双向链表节点结构体
typedef struct ListNode {
int val;
struct ListNode *prev;
struct ListNode *next;
} ListNode;
// 将二叉排序树转换为有序的双向链表
ListNode* treeToList(TreeNode* root) {
if (root == NULL) {
return NULL;
}
// 将左子树转换为有序的双向链表
ListNode *leftList = treeToList(root->left);
// 将右子树转换为有序的双向链表
ListNode *rightList = treeToList(root->right);
// 创建当前节点的双向链表节点
ListNode *curNode = (ListNode*)malloc(sizeof(ListNode));
curNode->val = root->val;
curNode->prev = NULL;
curNode->next = NULL;
// 将左子树的双向链表和当前节点连接起来
if (leftList != NULL) {
ListNode *leftTail = leftList;
while (leftTail->next != NULL) {
leftTail = leftTail->next;
}
leftTail->next = curNode;
curNode->prev = leftTail;
} else {
leftList = curNode;
}
// 将右子树的双向链表和当前节点连接起来
if (rightList != NULL) {
rightList->prev = curNode;
curNode->next = rightList;
}
return leftList;
}
// 创建二叉树节点
TreeNode* createNode(int val) {
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 插入节点到二叉排序树中
TreeNode* insertNode(TreeNode *root, int val) {
if (root == NULL) {
return createNode(val);
}
if (val < root->val) {
root->left = insertNode(root->left, val);
} else {
root->right = insertNode(root->right, val);
}
return root;
}
// 中序遍历二叉树
void inorderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
// 打印双向链表
void printList(ListNode *head) {
ListNode *curNode = head;
while (curNode != NULL) {
printf("%d ", curNode->val);
curNode = curNode->next;
}
printf("\n");
}
int main() {
// 创建二叉排序树
TreeNode *root = NULL;
root = insertNode(root, 5);
insertNode(root, 3);
insertNode(root, 7);
insertNode(root, 2);
insertNode(root, 4);
insertNode(root, 6);
insertNode(root, 8);
// 中序遍历二叉树
printf("Inorder traversal of binary search tree:\n");
inorderTraversal(root);
printf("\n");
// 将二叉排序树转换为有序的双向链表
ListNode *head = treeToList(root);
// 打印双向链表
printf("Doubly linked list:\n");
printList(head);
return ;
}
```
阅读全文