基础算法之二叉树 1 平衡二叉树的判断

什么是平衡二叉树?

平衡二叉树指的是二叉树的每一个节点的左子树和右子树的高度差为不大于1

所以由此推出判断的条件有

  1. 每一个子树如果有一个出现不是平衡二叉树的话就一定不是平衡二叉树
  2. 如果遍历得到的某一个节点出现了,二叉树的高度之差大于1也不是二叉树
  3. 每次遍历之后都要返回左右子树的深度
  4. 如果该节点满足二叉树的要求,该二叉树的深度就是它下面最高的子树的大小加上自己的大小
#include <iostream>
#include <math.h>
#include <stdlib.h>


using namespace std;

//返回值的类
class returnData{
  public:
     bool isB;
     int h;
     returnData(bool isb,int h)
     {
         this->isB = isb;
         this->h = h;
     }
};

//树的节点类
class Node{

public:
   Node * left;
   Node * right;
   int value;
   Node(int val)
   {
     left = NULL;
     right = NULL;
     this->value  = val;
   }

};

//递归遍历判断是否为平衡二叉树的函数
returnData * process(Node * Head)
{
   returnData * val;
   if(Head == NULL)
     return val = new returnData(true,0);

   returnData * left = process(Head->left);
   returnData * right = process(Head->right);

   if(!left->isB)
     return val = new returnData(false,0);
   if(!right->isB)
     return val = new returnData(false,0);

   int delta = left->h > right->h ? left->h - right->h : right->h - left->h;


   if(delta > 1)
      return val = new returnData(false,0);
   else
      return val = new returnData(true,max(left->h , right->h) + 1);

}
/***调用递归判断函数***/
bool isBalance(Node * head)
{
    return process(head)->isB;
}

/***创建一棵树进行测试 ***/
int main()
{
    Node * head = new Node(1);
    head->left = new Node(2);
    head->right = new Node(3);
    head->left->left = new Node(4);
    head->left->right = new Node(5);
    head->right->left = new Node(6);
    head->right->right = new Node(7);

    cout <<  isBalance(head) <<endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_42427338/article/details/89300750