C 如何以数组形式获取二叉树的全部内容?
我有一个表示二叉树的C结构:C 如何以数组形式获取二叉树的全部内容?,c,algorithm,binary-tree,C,Algorithm,Binary Tree,我有一个表示二叉树的C结构: struct btree { char *word; int frequency; struct btree *left; struct btree *right; }; 我想创建一个函数btree\u list(struct btree*),它返回传递给它的二叉树中所有btree对象的数组。秩序并不重要 以下是此函数如何工作的示例: struct btree *T = populate_with_random_value
struct btree {
char *word;
int frequency;
struct btree *left;
struct btree *right;
};
我想创建一个函数btree\u list(struct btree*)
,它返回传递给它的二叉树中所有btree
对象的数组。秩序并不重要
以下是此函数如何工作的示例:
struct btree *T = populate_with_random_values();
struct btree *entries = (struct btree*) malloc(sizeof(struct btree) * btree_size(T));
entries = btree_list(T);
while (*entries != NULL) {
printf("There are %d occurences of the word %s", entries->frequency, entries->word);
entries++;
}
此外,对于
条目中的每个元素E
,E->left
和E->right
应设置为NULL
,因为它们在技术上未被使用。我该如何实现这一点呢?那么,您想要一个前序、内序还是后序遍历
下面是伪代码中的预订单示例:(归功于)
为了让它返回一个节点列表,您必须对此进行一些调整,但遍历树背后的想法就在这里。与其返回数组,不如传递其基址,让您的生活更轻松,并返回数组的计数:
int TraverseTree(int arr[],btreenode *root, int depth)
{
static int count = 0;
if (root)
{
count++;
TraverseTree(arr,root->right,depth+1);
arr[depth]=root->data;
TraverseTree(arr,root->left, depth+1);
}
return count;
}
这可能是阵列:
typedef struct {
struct btree **data;
size_t count;
} t_tbl;
t_tbl *tbl_create(size_t count)
{
t_tbl *new = NULL;
if (count > 0) {
new = malloc(sizeof(t_tbl));
new->data = malloc(count * sizeof(struct btree *));
new->count = 0;
}
return new;
}
void tbl_destroy(t_tbl *table)
{
if (table) {
free(table->data);
free(table);
}
}
这可能是一个过程:
void btree_populate_array(const t_node *root, t_tbl *table)
{
if (root->left) btree_populate_array(root->left, table);
table->data[table->count++] = root;
if (root->right) btree_populate_array(root->right, table);
}
if (root) {
t_tbl *table = tbl_create(btree_size);
btree_populate_array(root, table);
/* Do stuff with array */
tbl_destroy(table);
}
如果您不知道btree的大小,则必须检查malloc
:
void btree_count(const t_node *root, size_t *count)
{
if (root->left) btree_count(root->left, count);
(*count)++;
if (root->right) btree_count(root->right, count);
}
size_t btree_size = 0;
if (root) {
btree_count(root, &btree_size);
}
您知道,两行malloc了条目
数组,并立即用下一行泄漏所有内存,这将覆盖刚刚由btree\u list的返回值所接收的地址。所以我希望它不会那样工作。
void btree_count(const t_node *root, size_t *count)
{
if (root->left) btree_count(root->left, count);
(*count)++;
if (root->right) btree_count(root->right, count);
}
size_t btree_size = 0;
if (root) {
btree_count(root, &btree_size);
}