将二叉搜索树转化为排序的双向链表,c语言实现
时间: 2024-03-25 08:36:21 浏览: 55
以下是将二叉搜索树转化为排序的双向链表的C语言实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode *prev = NULL;
void convert(struct TreeNode *root, struct TreeNode **head) {
if (root == NULL) {
return;
}
convert(root->left, head);
if (prev == NULL) {
*head = root;
} else {
prev->right = root;
root->left = prev;
}
prev = root;
convert(root->right, head);
}
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 TreeNode *head = NULL;
convert(root, &head);
// 打印双向链表
struct TreeNode *p = head;
while (p != NULL) {
printf("%d ", p->val);
p = p->right;
}
// 释放内存
free(root->left->left);
free(root->left->right);
free(root->left);
free(root->right);
free(root);
return 0;
}
```
该算法的主要思路是中序遍历二叉搜索树,并在遍历过程中将节点连接为双向链表。具体实现时,需要用一个全局变量`prev`指向当前节点的前一个节点,以便在遍历当前节点时,将前一个节点和当前节点连接起来。另外,需要使用一个指向头节点的指针`head`,以便在遍历结束后返回头节点。
阅读全文