【发布时间】: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