【问题标题】:Searching for a number inside a tree在树中搜索数字
【发布时间】:2021-04-06 11:57:42
【问题描述】:
typedef struct Tree{
    int value;
    struct Tree* leftNode;
    struct Tree* rightNode;
}Tree;

Tree* Is_Existing_Number(Tree *root, int number, bool found) {

    if (!root || found)
        return root;

    if (root->value == number)
        found = true;

    else {
         Is_Existing_Number(root->leftNode, number, found);
         Is_Existing_Number(root->rightNode, number, found);
    }
}

我有一个问题:我想查找一棵树中是否有特定的数字。如果是这样,我希望函数返回一个指向它的指针,所以基本上我想遍历整个树并检查树中是否存在该数字。

为什么这段代码不起作用?

【问题讨论】:

  • 你的else子句如果不为null,则需要返回搜索左节点的值;否则,它需要通过搜索正确的节点返回值。
  • btw.. 如果在查找值时访问了两个分支,那么使用 BST 的目的是什么?
  • 您的代码假设您有一个二叉树,而不是二叉搜索树。如果你有一棵二叉搜索树,那么如果当前节点不包含你要的值,你就知道是看左子树(因为寻找的值小于当前节点)还是右子树(因为寻求的价值更大)。这减少了所需的搜索量。您还需要为 if (root->value == number) 情况返回一个值(return root; — 无需设置 found)。确实,您根本不需要found

标签: c recursion binary-tree binary-search-tree


【解决方案1】:

我假设您使用二叉搜索树 (BST)。否则,使用二叉树将毫无意义;数组/列表将适合模式。

BST 中的值是有序的。因此存储在子节点(即leftNode)分支中的所有值都大于当前节点中的值。另一个子节点(即rightNode)中的值小于当前节点中的值。

这让它在查找值时跳过整个子分支。

代码应如下所示:

Tree *FindNumber(Tree* root, int value) {
  if (root == NULL) { // hit the leaf, value is absent
    return NULL;
  } else if (root->value == value) { // value found
    return root;
  } else if (root->value > value) { // try left node
    return FindNumber(root->leftNode, value);
  } else {
    return FindNumber(root->rightNode, value); // try right node
  }
}

您可能需要根据树的排序方式交换左右节点的角色。

如果函数返回非 NULL,则该值存在于树中。

【讨论】:

  • 在左侧节点中具有较小的值而在右侧节点中具有较大的值更为常见,但这是可以由编码器做出的决定。只要一切都是一致的,任何一个定义都有效。
猜你喜欢
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2018-05-03
  • 2018-03-31
相关资源
最近更新 更多