【学习点滴-数据结构-二叉树】判断二叉树是否是平衡二叉树

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define LEAF -1

typedef struct BTreeNode{
     BTreeNode* lchild;
     BTreeNode* rchild;
     int value;       
        
}BTreenode,*Btree;

BTreenode* createTree(){
     BTreeNode* T;
     int t;  
     scanf("%d",&t);
     if(t==LEAF){
          T = NULL;
     }else{
          T = (BTreeNode *) malloc(sizeof(BTreeNode));
          T->value = t;
          T->lchild = createTree();
          T->rchild = createTree();    
     }
     return T;
}

int getHeight(BTreeNode* root){
     if(root == NULL){
          return 0;   
     }
     int left = 0,right = 0;
     if(root->lchild !=NULL){
         left = getHeight(root->lchild);               
     }
     if(root->rchild != NULL){
         right = getHeight(root->rchild);                            
     }
     return (left>right?left:right) + 1;    
}

int isBalancedTree(BTreeNode * root){
    if(root == NULL){
        return 1;        
    }
    int left = 0,right = 0;
    if(root->lchild != NULL){
        left =  getHeight(root->lchild);             
    }
    if(root->rchild != NULL){
        right = getHeight(root->rchild);                
    }
    int distance = (left > right)?(left - right):(right - left);
    if(distance > 1){
        return 0;            
    }else{
     
        return (isBalancedTree(root->lchild) && isBalancedTree(root->rchild)); 
    }  
}


main(){
    BTreeNode * root;
    root = createTree();
    printf("height: %d \n",getHeight(root));
    printf("balance: %d \n",isBalancedTree(root));
    system("pause");
    return 0;       
}


你可能感兴趣的:(数据结构,struct,null,System,include,distance)