我试图查看树 A 是否是树 B 的前序遍历,为此,我创建了两棵树,它们在遍历期间应该保存值。但是,经过数小时的调试后,我发现树的值始终为 0。我对为什么树的值为 0 感到困惑。我已经完成了大量的打印语句(其中一些我留在了发布的代码中下面),我似乎无法确定为什么会发生这种情况。有人可以将我推向正确的方向吗?我想也许该函数在退出时正在删除变量,为了解决问题,我让 preorder 函数返回树(如下所示),但是,树的输出始终为 0。
代码:
typedef struct node
{
// Each node holds a single integer.
int data;
// Pointers to the node's left and right children.
struct node *left, *right;
} node;
int tree_diff(node *a, node *b)
{
if (a == NULL && b == NULL)
return 0;
else if (a == NULL || b == NULL)
return 1;
else if (a->data != b->data)
return 1;
printf("A %d , B %d", a->data, b->data);
return tree_diff(a->left, b->left) || tree_diff(a->right, b->right);
}
node *preorder_recursive(node *root, node *A)
{
if (root == NULL)
return A;
printf("root %d ", root->data);
A = root;
printf("= data %d\n", A->data);
preorder_recursive(root->left, A->left);
preorder_recursive(root->right, A->right);
}
void postorder_recursive(node *root, node *B)
{
if (root == NULL)
return;
B = root;
postorder_recursive(root->left, B->left);
postorder_recursive(root->right, B->right);
printf("root %d ", root->data);
printf("= data %d\n", B->data);
}
int kindredSpirits(node *a, node *b)
{
// Get the preorder of a
node *A = malloc(sizeof(node));
A = preorder_recursive(a, A);
// Get the postorder of b
printf("\n\n");
node *B = malloc(sizeof(node));
postorder_recursive(b, B);
if(tree_diff(A,B) == 1)
return 0;
else
return 1;
}
测试用例:
#include <stdio.h>
#include <stdlib.h>
#include "KindredSpirits.h"
node *create_node(int data)
{
node *n = malloc(sizeof(node));
n->data = data;
n->left = n->right = NULL;
return n;
}
node *forest_fire(node *root)
{
if (root == NULL)
return NULL;
forest_fire(root->left);
forest_fire(root->right);
free(root);
}
int main(void)
{
node *root;
root = create_node(23);
root->left = create_node(12);
root->left->left = create_node(5);
root->left->right = create_node(18);
root->right = create_node(71);
root->right->right = create_node(56);
printf("%s\n", !kindredSpirits(root, root) ? "Success!" : "fail whale :(");
forest_fire(root);
return 0;
}