gpt4 book ai didi

c - 如何统计二叉树的总节点数

转载 作者:太空狗 更新时间:2023-10-29 15:15:57 26 4
gpt4 key购买 nike

我需要计算二叉树中节点的总数。当我执行这段代码时,现在出现了问题,它为节点总数提供了垃圾值。我程序的输出类似于 993814。应该是 7

如何解决这个问题?

#include<stdlib.h>
#include<stdio.h>

struct binarytree
{
int data;
struct binarytree * right, * left;
};

typedef struct binarytree node;

void insert(node ** tree, int val)
{
node *temp = NULL;
if(!(*tree))
{
temp = (node *)malloc(sizeof(node));
temp->left = temp->right = NULL;
temp->data = val;
*tree = temp;
return;
}

if(val < (*tree)->data)
{
insert(&(*tree)->left, val);
}
else if(val > (*tree)->data)
{
insert(&(*tree)->right, val);
}

}

void print_preorder(node * tree)
{
if (tree)
{
printf("%d\n",tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}

}

void print_inorder(node * tree)
{
if (tree)
{
print_inorder(tree->left);
printf("%d\n",tree->data);
print_inorder(tree->right);
}
}

int count(node *tree)
{
int c=0;

if (tree ==NULL)
return 0;

else
{
c += count(tree->left);
c += count(tree->right);
return c;
}
}

void print_postorder(node * tree)
{
if (tree)
{
print_postorder(tree->left);
print_postorder(tree->right);
printf("%d\n",tree->data);
}
}

int main()
{
node *root;
node *tmp;
int c;

root = NULL;
/* Inserting nodes into tree */
insert(&root, 9);
insert(&root, 10);
insert(&root, 15);
insert(&root, 6);
insert(&root, 12);
insert(&root, 17);
insert(&root, 2);

/* Printing nodes of tree */
printf("Pre Order Display\n");
print_preorder(root);

printf("In Order Display\n");
print_inorder(root);

printf("Post Order Display\n");
print_postorder(root);

printf("Number of node %d \n",c);

}

最佳答案

我宁愿在不使用局部变量的情况下在每次递归调用中返回总和。

int count(struct node *root){
if(root == NULL){
return 0;
}
else{
return 1 + count(root->left) + count(root->right);
}
}

关于c - 如何统计二叉树的总节点数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33228660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com