【问题标题】:How to find the depth of a specific node in a BST in c如何在c中找到BST中特定节点的深度
【发布时间】:2021-12-02 20:06:04
【问题描述】:

我正在尝试查找 c 中指针指出的特定节点的深度,但我似乎无法正确理解

int depth(Node *root, Node *N){
    // Need to find the root N
    // At the same time count how many depths you can go down
    
    // If the root is NULL, then no tree and return -1
    if (root == NULL){
        return -1;
    }
    // If the root node equals the node N, then return 0
    if (root->data == N->data){
        return 0;
    }
    // Search the tree and add one each time recursion called
    int count = -1;
    if (N->data < root->data){
        root->left->data = depth(root->left, N);
        count++;
    }
    else if (N->data > root->data){
        root->right->data = depth(root->right, N);
        count++;
    }
    else{
        
    }
    return count;
}

任何解决此问题的帮助将不胜感激。

【问题讨论】:

  • 搜索树时为什么要修改data
  • 为什么要把depth()的返回值赋值给root-&gt;left-&gt;data或者root-&gt;right-&gt;data来修改树的内容?
  • 我正在尝试递归搜索给定节点的树,并在每次递归后添加 1 以作为深度。我在 C 方面并不出色,所以我只是尽力而为
  • 首先为什么要修改数据?其次,count 似乎是函数的局部变量,虽然函数返回它,但在退出递归时不会累积它,因此它始终为 1。
  • 将BST的数据赋值给该数据所在的深度值也是没有意义的。

标签: c binary-search-tree depth


【解决方案1】:

此类函数的伪代码与此类似,假设 root = 0 级:

int search (const node_t* node, int level)
{
    if(node == NULL)
      return -1;
    if(node->data == key)
      return level;

    const node_t* node next;

    if(node->data < key)
      next = node->right;
    else if(node->data > key)
      next = node->left
    
    return search (next, level+1);
}

首先调用为search(root, 0);

尽管像往常一样,C 中的递归几乎可以肯定是任何问题的错误解决方案。上面的内容可以相当简单地重写为理智、可读、快速的循环。

【讨论】:

  • 那么您是否建议在 C 中迭代地执行此操作 - 解析指向根的指针以及指向要确定深度的值的指针,找到该值然后返回它的级别在 + 1 处?
  • @Fraser 是的,类似于上面的东西,但是用for(cost node_t* i=root; i!=NULL; i=next) { ... } 之类的东西来切换繁重的递归。递归在 C 中毫无用处,因为它永远不会比循环快,通常更慢,更危险,更容易出错,而且通常更难阅读。递归的主要用途是:混淆、打码、冒充、迷惑学生。
猜你喜欢
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 2020-09-08
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
  • 1970-01-01
相关资源
最近更新 更多