生成二叉排序树代码示例
时间: 2024-04-15 10:23:30 浏览: 25
生成二叉排序树(Binary Search Tree,BST)的代码示例如下:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
def buildBST(arr):
root = None
for val in arr:
root = insert(root, val)
return root
```
这段代码定义了一个`TreeNode`类,表示二叉树的节点。`insert`函数用于向二叉排序树中插入一个节点,`buildBST`函数用于根据给定的数组构建一个二叉排序树。
相关问题
从文件读入整数序列,生成二叉排序树
以下是使用 Python 语言从文件中读入整数序列,生成二叉排序树的示例代码:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
if root is None:
return TreeNode(val)
elif val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
def build_BST(filename):
root = None
with open(filename, 'r') as f:
for line in f:
val = int(line.strip())
root = insert(root, val)
return root
```
以上代码中,`TreeNode` 表示二叉排序树的节点,包含值 `val`,以及左右子节点 `left` 和 `right`。`insert` 函数用于向二叉排序树中插入新节点,并保证树的排序性质。`build_BST` 函数用于从文件中读入整数序列,并构建二叉排序树。该函数首先读取文件中的每一行,将字符串转换为整数,并将其插入到二叉排序树中。最终返回根节点 `root`。
从文件读入整数序列,生成二叉排序树,用C语言实现
以下是使用 C 语言从文件中读入整数序列,生成二叉排序树的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* insert(struct TreeNode* root, int val) {
if (root == NULL) {
root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = val;
root->left = NULL;
root->right = NULL;
} else if (val < root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
struct TreeNode* build_BST(char* filename) {
struct TreeNode* root = NULL;
FILE* fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file.\n");
return NULL;
}
char buf[1024];
while (fgets(buf, 1024, fp) != NULL) {
int val = atoi(buf);
root = insert(root, val);
}
fclose(fp);
return root;
}
```
以上代码中,`struct TreeNode` 表示二叉排序树的节点,包含值 `val`,以及左右子节点 `left` 和 `right`。`insert` 函数用于向二叉排序树中插入新节点,并保证树的排序性质。`build_BST` 函数用于从文件中读入整数序列,并构建二叉排序树。该函数首先打开文件,读取每一行并将字符串转换为整数,然后将其插入到二叉排序树中。最终返回根节点 `root`。注意在使用完文件后需要关闭文件句柄,避免资源泄露。