c语言实现将二叉查找树变为有序的双向链表
时间: 2024-06-13 20:05:42 浏览: 111
以下是C语言实现将二叉查找树变为有序的双向链表的代码和注释说明:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 定义双向链表结构体
struct ListNode {
int val;
struct ListNode *prev;
struct ListNode *next;
};
// 将二叉查找树转换为有序的双向链表
struct ListNode* treeToDoublyList(struct TreeNode* root) {
if (root == NULL) {
return NULL;
}
struct ListNode *head = NULL, *tail = NULL;
// 中序遍历二叉树
inorder(root, &head, &tail);
// 将双向链表首尾相连
head->prev = tail;
tail->next = head;
return head;
}
// 中序遍历二叉树
void inorder(struct TreeNode* root, struct ListNode** head, struct ListNode** tail) {
if (root == NULL) {
return;
}
inorder(root->left, head, tail);
// 将当前节点转换为双向链表节点
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = root->val;
node->prev = *tail;
node->next = NULL;
if (*tail != NULL) {
(*tail)->next = node;
}
*tail = node;
if (*head == NULL) {
*head = node;
}
inorder(root->right, head, tail);
}
// 测试代码
int main() {
// 构造二叉查找树
struct TreeNode *root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 4;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->left->val = 1;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->right->val = 3;
root->left->right->left = NULL; root->left->right->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 5;
root->right->left = NULL;
root->right->right = NULL;
// 将二叉查找树转换为有序的双向链表
struct ListNode *head = treeToDoublyList(root);
// 遍历双向链表
struct ListNode *cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
return 0;
}
```
阅读全文