在非空二叉排序树中求出指定关键字的结点的层次C语言完整代码
时间: 2024-02-26 22:58:33 浏览: 23
以下是求出指定关键字的结点的层次的 C 语言完整代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int key;
struct TreeNode *left;
struct TreeNode *right;
};
int find_node_level(struct TreeNode *root, int key) {
/*
* 在非空二叉排序树中查找指定关键字的结点,并返回其层次
*/
int level = 1;
struct TreeNode *node = root;
while (node != NULL) {
if (node->key == key) {
return level;
}
else if (node->key < key) {
node = node->right;
}
else {
node = node->left;
}
level++;
}
// 没有找到指定结点,返回 -1
return -1;
}
int main() {
// 创建二叉排序树
struct TreeNode *root = (struct TreeNode *) malloc(sizeof(struct TreeNode));
root->key = 5;
root->left = (struct TreeNode *) malloc(sizeof(struct TreeNode));
root->left->key = 3;
root->left->left = (struct TreeNode *) malloc(sizeof(struct TreeNode));
root->left->left->key = 1;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (struct TreeNode *) malloc(sizeof(struct TreeNode));
root->left->right->key = 4;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (struct TreeNode *) malloc(sizeof(struct TreeNode));
root->right->key = 7;
root->right->left = (struct TreeNode *) malloc(sizeof(struct TreeNode));
root->right->left->key = 6;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode *) malloc(sizeof(struct TreeNode));
root->right->right->key = 8;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 查找指定结点的层次
int level = find_node_level(root, 4);
printf("The level of the node is: %d\n", level);
return 0;
}
```
在此示例代码中,我们创建了一个二叉排序树,并查找了关键字为 4 的结点的层次。注意,如果没有找到指定结点,则返回 -1。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)