一组有序顺序表的二叉判定树唯一吗
时间: 2024-02-22 12:57:01 浏览: 17
不唯一。对于一个有序顺序表,可以构建多个不同的二叉判定树。例如,对于有序顺序表 [1, 2, 3, 4],可以构建以下两个二叉判定树:
```
2 3
/ \ / \
1 3 2 4
/ \ / \
4 - 1 -
```
这两个二叉判定树的结构不同,但都可以通过中序遍历得到有序顺序表 [1, 2, 3, 4]。因此,有序顺序表的二叉判定树不是唯一的。
相关问题
c语言代码,顺序表建立二叉排序树
下面是用 C 语言实现顺序表建立二叉排序树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// 定义二叉树节点结构体
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 定义顺序表结构体
typedef struct SeqList {
int data[MAX_SIZE];
int length;
} SeqList;
// 从顺序表中创建二叉排序树
void createBST(SeqList list, TreeNode** root) {
int i;
for (i = 0; i < list.length; i++) {
int data = list.data[i];
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;
if (*root == NULL) {
*root = node;
} else {
TreeNode* p = *root;
while (p != NULL) {
if (data < p->data) {
if (p->left == NULL) {
p->left = node;
break;
} else {
p = p->left;
}
} else {
if (p->right == NULL) {
p->right = node;
break;
} else {
p = p->right;
}
}
}
}
}
}
// 中序遍历二叉树
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
int main() {
SeqList list = {{7, 2, 8, 1, 5, 3, 6, 4}, 8};
TreeNode* root = NULL;
createBST(list, &root);
inorderTraversal(root);
return 0;
}
```
以上代码实现了从顺序表中创建二叉排序树,并对二叉排序树进行中序遍历输出。
输入顺序相同,二叉排序树是否唯一
不一定唯一。如果输入的元素是有序的,如 $1,2,3,4,5$,则二叉排序树唯一;但如果输入的元素是无序的,如 $4,2,5,1,3$,则可以构造出多个不同的二叉排序树。例如,下图所示的两棵二叉排序树都是由 $4,2,5,1,3$ 构造而成,但它们不同。
```
4 4
/ \ / \
2 5 2 5
/ \ / \
1 3 1 3
```
因此,二叉排序树的唯一性与输入元素的顺序有关。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)