質問

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

struct node{
  int data;
  struct node* left;
  struct node* right;
};

struct node* newNode(int data){
  struct node* new_node=(struct node*)malloc(sizeof(struct node));
  new_node->data=data;
  new_node->left=NULL;
  new_node->right=NULL;
  return new_node;
}

int maxi(int a,int b){
  if(a > b)
    return a;
  else
    return b;
}

   int height(struct node* tree){
if(tree==NULL)
    return 0;
return 1 + maxi(height(tree->left),height(tree->right));
    }

   /*function to determine if a tree is height balanced */
   int htbalance(struct node* tree){
int lheight,rheight;
if(tree==NULL)
    return 1;

    lheight=height(tree->left);
    rheight=height(tree->right);/*
    lbal=htbalance(tree->left);
    rbal=htbalance(tree->right);*/
    if(htbalance(tree->left) && htbalance(tree->right) && ((lheight - rheight) <= 1))
        return 1;

    return 0;

       }



    int main(void){
 struct node* tree=newNode(1);
 tree->left=newNode(2);
 tree->left->right=newNode(3);
 tree->left->right->left=newNode(5);
 tree->left->right->left->left=newNode(56);
 clrscr();
 if(htbalance)
    printf("tree is height balanced\n");
 else
    printf("tree is not height balanced \n");
getch();
return 0;
   }

Hi Folks, The above C code I have written to check whether the binary tree is balanced or not.But its always giving the output as 'the tree is balanced' even when the input is an Inbalanced tree.Could you please check what mistake I am making.

役に立ちましたか?

解決

if(htbalance)
    printf("tree is height balanced\n");

Here you only check whether htbalance, a pointer to a function, is NULL or not. Of course it is non-NULL, and thus you always get true.

You should call htbalance() and check its return value.

if (htbalance(tree))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top