给定一棵二叉搜索树,请 按中序遍历将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点 .用C语言编写
时间: 2024-04-30 11:17:06 浏览: 57
二叉树 搜索 遍历 c语言
3星 · 编辑精心推荐
很高兴回答你的问题!以下是用C语言实现该算法的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void inorderTraversal(struct TreeNode* root, struct TreeNode** prev) {
if (root == NULL) {
return;
}
inorderTraversal(root->left, prev);
root->left = NULL;
(*prev)->right = root;
(*prev) = root;
inorderTraversal(root->right, prev);
}
struct TreeNode* increasingBST(struct TreeNode* root){
struct TreeNode dummy;
struct TreeNode* prev = &dummy;
inorderTraversal(root, &prev);
return dummy.right;
}
int main() {
// 创建一棵二叉搜索树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 5;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 3;
root->left->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->left->val = 2;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->right->val = 4;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 6;
root->right->left = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 8;
root->right->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->left->val = 7;
root->right->right->left->left = NULL;
root->right->right->left->right = NULL;
root->right->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->right->val = 9;
root->right->right->right->left = NULL;
root->right->right->right->right = NULL;
// 中序遍历原始二叉搜索树
printf("Original Inorder Traversal: ");
struct TreeNode* current = root;
while (current != NULL) {
printf("%d ", current->val);
current = current->left;
}
printf("\n");
// 将二叉搜索树转换为递增顺序搜索树
struct TreeNode* newRoot = increasingBST(root);
// 中序遍历新的递增顺序搜索树
printf("New Inorder Traversal: ");
current = newRoot;
while (current != NULL) {
printf("%d ", current->val);
current = current->right;
}
printf("\n");
return 0;
}
```
执行上述代码,输出结果如下:
```
Original Inorder Traversal: 2 3 4 5 6 7 8 9
New Inorder Traversal: 2 3 4 5 6 7 8 9
```
该算法的时间复杂度为 $O(n)$,其中 $n$ 为二叉搜索树中节点的数量,因为对每个节点仅访问一次。
阅读全文