70,037
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "D:\uthash库\uthash.h"
#include "xuliehua.h"
/*
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
typedef struct hashnode {
char key[20000];
struct TreeNode* node;
int cnt;
UT_hash_handle hh;
}Hashnode;
char * mydfs(struct TreeNode* root, Hashnode* USER)
{
if (root == NULL) //到达叶子节点后面的空节点
return "#";
char* string = (char*)calloc(20000, sizeof(char));
sprintf(string, "%d", root->val); //将当前节点val存入字符串
strcat(string, mydfs(root->left, USER)); //该字符串衔接左节点形成的字符串
strcat(string, mydfs(root->right, USER)); //该字符串衔接右节点形成的字符串
Hashnode* tm = NULL;
HASH_FIND_STR(USER, string, tm); //以该字符串为key,查找hashmap
if (tm == NULL)
{
tm = (Hashnode*)calloc(1, sizeof(Hashnode));
strcpy(tm->key, string);
tm->node = root;
tm->cnt = 1;
HASH_ADD_STR(USER, key, tm);
}
else
tm->cnt++;
return string;
}
struct TreeNode** findDuplicateSubtrees(struct TreeNode* root, int* returnSize) {
if (root == NULL)
{
*returnSize = 0;
return NULL;
}
Hashnode* USER = NULL;
mydfs(root, USER);
int len = HASH_COUNT(USER);
struct TreeNode** res = (struct TreeNode**)calloc(len, sizeof(struct TreeNode));
Hashnode* cur, * tm;
HASH_ITER(hh, USER, cur, tm)
{
if (cur->cnt > 1)
{
res[(*returnSize)++] = cur->node;
}
free(cur);
}
free(USER);
return res;
}
如上代码是力扣中的题目:寻找重复的子树。
现在的问题是,程序执行完之后USER是空的,调试了也发现每次递归之后USER就成NULL了,请问这是什么原因造成的呢?
任意一本C语言教材在函数那一章都会强调,函数参数在调用的时候是单向传值的。
也就是说你在被调用函数里面修改的是参数副本,不存在回传机制。
改了一下代码,将USER改成全局变量,mydfs(struct TreeNode * root)该为一个参数,直接在函数中调用全局变量通过了。
但是还是没明白,为什么做参数的时候不行了?难道是USER是局部变量,每次传入mydfs时会重新定义?清空?原理是什么呢?