简体   繁体   English

如何在不将级别作为参数传递给 function 的情况下找到二叉树中节点的级别?

[英]How to find the level of a node in a binary tree without passing the level as an argument to the function?

This is the code to find the level while passing level as an argument to the function.这是在将 level 作为参数传递给 function 时查找级别的代码。

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;}

But how to find without passing level as an argument?但是如何在不通过级别作为参数的情况下找到? Should I have level in my node struct?我的节点结构中应该有级别吗? How to initialize it then?那怎么初始化呢?

This is my struct and insert right now:这是我现在的结构和插入:

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;
}

Your best option is probably to convert you recursive algorithm to an iterative version.您最好的选择可能是将递归算法转换为迭代版本。 Then you can store the level in a local variable, and keep track of your search path using a stack (for depth first search (DFS)).然后您可以将级别存储在局部变量中,并使用堆栈跟踪您的搜索路径(用于深度优先搜索 (DFS))。

You can, as you mentioned, store the level in each node, but that is technically passing it as an argument.正如您所提到的,您可以将级别存储在每个节点中,但这在技术上是将其作为参数传递。 On insert, you set the level of the new node to the level of the parent + 1. Here is a minimal implementation of this idea:在插入时,您将新节点的级别设置为父节点的级别 + 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM