在非空二叉排序树中求出指定关键字的结点的层次C语言完整代码mian函数简单点
时间: 2024-02-26 11:58:44 浏览: 67
数据结构课程设计建立二叉树并求指定结点路径程序源代码.doc
以下是求出指定关键字的结点的层次的 C 语言完整代码,其中 `main` 函数部分更简单:
```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 key = 4;
int level = find_node_level(root, key);
if (level == -1) {
printf("The node with key %d is not found.\n", key);
}
else {
printf("The level of the node with key %d is: %d\n", key, level);
}
return 0;
}
```
在此示例代码中,我们创建了一个二叉排序树,并查找了关键字为 4 的结点的层次。如果找到了指定结点,则输出其层次;否则,输出未找到指定结点的提示信息。
阅读全文