【问题标题】:How to find the level of a node in a binary tree without passing the level as an argument to the function?如何在不将级别作为参数传递给函数的情况下找到二叉树中节点的级别?
【发布时间】:2021-03-19 06:41:14
【问题描述】:

这是在将级别作为参数传递给函数时查找级别的代码。

int findLevel(node* root, node* ptr,
    int level = 0) {
if (root == NULL)
    return -1;
if (root == ptr)
    return level;
// If NULL or leaf Node
if (root->left == NULL && root->right == NULL)
    return -1;
// Find If ptr is present in the left or right subtree.
int levelLeft = findLevel(root->left, ptr, level + 1);
int levelRight = findLevel(root->right, ptr, level + 1);
if (levelLeft == -1)
    return levelRight;
else
    return levelLeft;}

但是如何在不传递 level 作为参数的情况下找到?我的节点结构中应该有级别吗?那怎么初始化呢?

这是我的结构并立即插入:

typedef struct Node{
    int value;
    bst left;
    bst right;
} node;

node* bst_insert (node* root, int value){
    if(root == NULL){
        root = (node*) malloc(sizeof(node));
        root->value = value;
        root->left = NULL;
        root->right = NULL;
    }
    else{
        if(value > root->value)
            root->right = bst_insert(root->right, value);
        else
            root->left = bst_insert(root->left, value);
    }

    return root;
}

【问题讨论】:

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


    【解决方案1】:

    您最好的选择可能是将递归算法转换为迭代版本。然后您可以将级别存储在局部变量中,并使用堆栈跟踪您的搜索路径(用于深度优先搜索 (DFS))。

    正如您所提到的,您可以将级别存储在每个节点中,但这在技术上是将其作为参数传递。在插入时,您将新节点的级别设置为父节点的级别 + 1。这是此想法的最小实现:

    #include <assert.h>
    #include <stdlib.h>
    
    struct node;
    
    struct node {
        int value;
        int level;
        struct node *left;
        struct node *right;
    };
    
    struct node *node_new(int value, int level) {
        struct node *n = malloc(sizeof(struct node));
        assert(n);
        n->value = value;
        n->level = level;
        n->left = 0;
        n->right = 0;
        return n;
    }
    
    void node_insert(struct node **current, int value) {
        // leaf
        struct node **next = value < (*current)->value ? &(*current)->left : &(*current)->right;
        if(!*next) {
            *next = node_new(value, (*current)->level + 1);
            return;
        }
    
        // non-leaf
        node_insert(next, value);
    }
    
    int main() {
        struct node *root = node_new(10, 0);
        node_insert(&root, 5);
        node_insert(&root, 20);
        node_insert(&root, 30);
    }
    

    【讨论】:

    • 这个怎么实现:'你把当前节点的级别设置为父节点的级别+1'?
    • 修复您的 bst_insert 以将每个新节点连接到您的树。我会在您当前的代码中将 root 重命名为 current 。根节点指针通常存储在结构树中。当您插入第一个节点时,您注意到您的根节点为空,因此您在它的节点中将 level 设置为 0(或 1,具体取决于您要如何计数)。然后在下一个插入中确定新叶子是否向左和向右移动,然后设置,例如,current->left = malloc(sizeof(node) 和 current->left->height = current->height + 1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2014-12-24
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    相关资源
    最近更新 更多