问题描述
我必须使用 DFS 搜索二叉树才能找到节点。 (tok 是我正在搜索的字符串)。如果找到它,它必须返回它为找到它而遍历的节点数。如果不是,则必须返回 -1。
我尝试了很多递归解决方案,但老实说,我很难过。我可能没有正确返回值。
测试用例: 假设我有一棵树,根名为“John”。“John”作为左孩子“Shayne”和右孩子“Eric”。此外,“Shayne”有一个左孩子“Max”。输出对于 John、Shayne 和 Max 来说是正确的。但是Eric的输出应该是4,因为我遍历john然后shayne然后max然后Eric(考虑到我先左后右),但是对于Eric,我得到了3的输出
使用精确的测试用例进行编辑。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char* name;
char* tea;
struct node* left;
struct node* right;
};
typedef struct node Node;
int depth(struct node* root);
int dfs(struct node* root,char* tok);
int main() {
Node* John = (Node*)malloc(sizeof(Node));
John->left = NULL;
John->right = NULL;
John->name = "John";
Node* Shayne = (Node*)malloc(sizeof(Node));
Shayne->left = NULL;
Shayne->right = NULL;
Shayne->name = "Shayne";
Node* Eric = (Node*)malloc(sizeof(Node));
Eric->left = NULL;
Eric->right = NULL;
Eric->name = "Eric";
Node* Max = (Node*)malloc(sizeof(Node));
Max->left = NULL;
Max->right = NULL;
Max->name = "Max";
John->left = Shayne;
Shayne->left = Max;
John->right = Eric;
printf("%d",dfs(John,"Eric"));
}
int depth(struct node* root) {
if (root == NULL) {
return 0;
}
int l = depth(root->left);
int r = depth(root->right);
int d = max(l,r) + 1;
return d;
}
int dfs(struct node* root,char* tok) {
if (root == NULL) {
return 0;
}
if (strcmp(root->name,tok) == 0) {
return 1;
}
else {
int l = dfs(root->left,tok);
if (l != -1) {
return 1 + l;
}
int r = dfs(root->right,tok);
if (r != -1) {
return 1+l+ r;
}
return -1;
}
}
解决方法
当在直接子节点中找到该值以生成节点数时,您正确地将返回值加 1。但这也意味着您将2返回给您的父母。
您必须将测试更改为
if (l != -1) { //found on left child
return 1 + l;
}
,
你的函数唯一的问题是,当你从子节点返回时,你总是用 1 检查 l 的值,例如:
int l = dfs(root->left,tok);
if (l == 1) { //found on left child
return 1 + l;
}
这对于前 2 个节点可以正常工作,但是返回的值变为 2,3,4,.... 在这种情况下它将跳过 if 并再次返回 -1,因此要解决这个问题好的方法是检查返回值是否不是 -1,例如:
int l = dfs(root->left,string);
if (l != -1) {
return 1 + l;
}
int r = dfs(root->right,string);
if (r != -1) {
return 1 + r;
}
希望这能给你答案。