2015-10-20 89 views
3

我需要计算二叉树中的节点总数。现在问题出现在我执行这段代码时,它给出了节点总数的垃圾值。我的程序的输出是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); 

} 
+0

如果通过在insert()中递增和在remove()上递减来追踪内部计数,那么最简单。 –

回答

2

你声明c,但不是初始化无处不在,也没有在任何地方使用。 然后你打印c的值,它给你垃圾值。

您可以修复你的count(node *tree)功能

int count(node *tree) 
{ 
    int c = 1;    //Node itself should be counted 
    if (tree ==NULL) 
     return 0; 
    else 
    { 
     c += count(tree->left); 
     c += count(tree->right); 
     return c; 
    } 
} 

通过返回在每次递归调用之和不使用局部变量main

int main() 
{ 
    ............. 
    ............. 


    c = count(root);  //number of node assign to c 
    printf("Number of node %d \n",c); 
} 
+0

int count(node * tree) { int c = 0; if(tree == NULL) return 0;其他 c + = count(tree-> left); c + = count(tree-> right); return c; } }'我在这里使用。 – acer

+0

这里'int c = 0'是'count(node * tree)'函数的局部变量,也不会从'main'调用它。 – ashiquzzaman33

+0

okey,你能告诉我,如何将这个c调用到main方法中? – acer

2

我宁愿做补充。

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