高度平衡的C树

时间:2014-05-09 09:13:41

标签: c struct tree

#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;
   }

嗨伙计们, 我编写的上述C代码是为了检查二叉树是否平衡。但是即使输入是Inbalanced树,它也总是将输出设为'树是平衡的'。请你检查一下我犯了什么错误。

1 个答案:

答案 0 :(得分:0)

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

在这里,您只需检查htbalance(指向函数的指针)是否为NULL。当然它是非NULL的,因此你总能得到真实。

您应致电 htbalance()并检查其返回值。

if (htbalance(tree))