c - 打印键所在的树的级别
问题描述
1 - 读取 n 个数字的序列并将其插入二叉搜索树。(我做了这部分没有任何问题。)
Node *insert(Node **root, int k)
{
if(*root == NULL)
{
Node *newNode = (Node *)malloc(sizeof(Node ));
if(newNode == NULL)
return NULL;
newNode->key = k;
newNode->left = NULL;
newNode->right = NULL;
(*root) = newNode;
return newNode;
}
if(k < (*root)->key)
return insert(&((*root)->left),k);
else
return insert((&(*root)->right),k);
}
2 - 读取一个数字并打印它所在的级别。如果键不存在于树中,则打印 -1。
这部分我不知道该怎么做,我只能计算出树的总高度。
int height(Node *aNode,int k) {
if (aNode == NULL) {
return -1;
}
int lefth = height(aNode->left,k);
int righth = height(aNode->right,k);
if (lefth > righth) {
return lefth + 1;
} else {
return righth + 1;
}
}
例子:
如果给定的数字是60 ,我必须打印1
如果给定的数字是27 ,我必须打印3
如果给定的数字是100 ,我必须打印-1
解决方案
你应该:
0
找到值时停止遍历并返回。-1
当两个孩子都没有找到该值时返回。
int height(Node *aNode,int k) {
if (aNode == NULL) {
return -1;
}
if (aNode->key == k) return 0; /* add this */
int lefth = height(aNode->left,k);
int righth = height(aNode->right,k);
if (lefth == -1 && righth == -1) return -1; /* add this */
if (lefth > righth) {
return lefth + 1;
} else {
return righth + 1;
}
}
推荐阅读
- node.js - 在 formData Angular 上设置标题
- javascript - React 应用程序没有以编程方式导航,必须在地址栏中使用链接刷新页面才能导航
- javascript - 使用 Word API 时“查找替换”中的位置移动
- reactjs - 测试 onclick标签渲染另一种成分酶
- sql - 选择在特定列上具有非重复值的条目(尽管其他列可能具有重复或非重复值)(SQL)
- html - 在 MediaQuery 中,一个元素在达到该宽度之前具有我们为它设置的某个宽度的某个属性是否正常?
- python - 将 Jenkins 输出日志中显示的命令的时间戳写入 .txt 或 .CSV 文件
- deployment - TFS 发布 - 按创建日期/时间的顺序按计划部署多个版本
- c++ - 包装二维网格索引
- python - 如何 webscrape virustotal 以获取结果 python