输入一棵二叉搜索树,将其转化成一个排序的双向链表,c语言实现
时间: 2024-03-17 20:43:55 浏览: 92
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;
};
// 递归函数,将二叉搜索树转化为排序的双向链表
void convertBSTtoDLL(struct TreeNode* root, struct ListNode **head, struct ListNode **tail) {
if (root == NULL) {
return;
}
// 对左子树进行转化
convertBSTtoDLL(root->left, head, tail);
// 将当前节点添加到双向链表中
struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->val = root->val;
node->prev = NULL;
node->next = NULL;
if (*head == NULL) {
*head = node;
} else {
(*tail)->next = node;
node->prev = *tail;
}
*tail = node;
// 对右子树进行转化
convertBSTtoDLL(root->right, head, tail);
}
// 主函数,调用递归函数将二叉树转化为排序的双向链表
struct ListNode* BSTtoDLL(struct TreeNode* root) {
if (root == NULL) {
return NULL;
}
struct ListNode *head = NULL;
struct ListNode *tail = NULL;
convertBSTtoDLL(root, &head, &tail);
return head;
}
// 测试函数
int main() {
// 创建一棵二叉搜索树
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = 4;
struct TreeNode *node1 = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node1->val = 2;
struct TreeNode *node2 = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node2->val = 5;
struct TreeNode *node3 = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node3->val = 1;
struct TreeNode *node4 = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node4->val = 3;
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = node4;
node2->left = NULL;
node2->right = NULL;
node3->left = NULL;
node3->right = NULL;
node4->left = NULL;
node4->right = NULL;
// 将二叉搜索树转化为排序的双向链表
struct ListNode *head = BSTtoDLL(root);
// 输出双向链表中的值
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
return 0;
}
```
该程序中,convertBSTtoDLL 函数是递归函数,用于将二叉搜索树转化为排序的双向链表;BSTtoDLL 函数是主函数,调用 convertBSTtoDLL 函数将二叉搜索树转化为排序的双向链表;最后,测试函数创建一棵二叉搜索树,将其转化为排序的双向链表,并输出双向链表中的值。
阅读全文