c - 大于 BST 中某个数字的节点之和

标签 c algorithm binary-search-tree

对于C语言中不可更改的二叉搜索树结构:

struct bstnode {
  int item;
  struct bstnode* left;
  struct bstnode* right;
};

struct bst {
  struct bstnode* root;
};

我们怎样才能找到大于数字(num)的值的总和?
(我们无法遍历整个树或将此 bst 转换为数组)。
函数声明为:

int sum_greater(struct bst * t, int num)

基本上,我的方法是使用递归:
当 num 等于当前节点中的 item 时,我们对这棵树的右侧部分求和。
当num大于当前节点中的item并且node->right大于num时,我们对这棵树的右侧部分求和。
但我不知道如何处理当前节点小于num的情况。

最佳答案

你把事情搞得太复杂了。您的基本情况是命中叶节点(您已经知道如何处理)。您有三种递归情况:

current > num
    result = current +
             recur on right child +
             recur on left  child
current = num
    result = current +
             recur on right child
current < num
    result = recur on right child

return result

您所能做的就是剪掉发现的太小的左子树。不要浪费精力展望 future :递归会很好地处理这个问题。

请注意,您不能提前停止对右 child 值的依赖:该 child 很可能拥有具有任意大值的右后代。

关于c - 大于 BST 中某个数字的节点之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45471941/

相关文章:

c++ - CUDA:在使用 cudaMallocPitch 分配的二维数组中查找数组索引

c - 指针不会显示到队列中的下一个条目

c - 管道上的非阻塞读取

algorithm - 是否存在针对小约束存在的 2 台相同机器和 N 个进程的最小完工时间调度的精确算法?

algorithm - 匈牙利 (Kuhn Munkres) 算法古怪

algorithm - 超几何函数的高效评估

C 二叉搜索树不给左右节点赋值?

c - 如何在 GTK 或 Cairo 中将纹理应用到四边形?

data-structures - 当我们有二叉搜索树时,为什么还需要二叉堆?

C++ 二进制搜索树错误