【发布时间】: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->left->data或者root->right->data来修改树的内容? -
我正在尝试递归搜索给定节点的树,并在每次递归后添加 1 以作为深度。我在 C 方面并不出色,所以我只是尽力而为
-
首先为什么要修改数据?其次,count 似乎是函数的局部变量,虽然函数返回它,但在退出递归时不会累积它,因此它始终为 1。
-
将BST的数据赋值给该数据所在的深度值也是没有意义的。
标签: c binary-search-tree depth