ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

检查二叉树是否为高度平衡树?

前开发者教程 2020年10月8日

题:

给定二叉树的根节点,请检查该树是否为高度平衡的树。

什么是高度平衡树?

如果左右的高度差不超过1,则称为高度平衡树。

这意味着该值应介于(-1,0,1)之间。

例:

考虑下图

如果我们只有1个节点,则高度为0。

二元树

如果我们有2个节点,

根节点16处的高度为1– 1 = 0

考虑下图
二元树

1.节点16处的高度为=正确的高度– left height

右高度= 2,左高度= 2。

因此,节点16的高度为0。

2.节点10处的高度为=正确的高度– left height

右高度= 1,左高度= 1。

因此,节点10的高度为0。

这样,我们必须计算每个节点的高度。如果该值在任何节点上都大于1,则该树不是高度平衡树。

 

C ++解决方案

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

// structure to hold binary tree node
struct Node
{
    int data;
    Node *left, *right;

    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};

int is_balanced(Node *node) 
{
    if (node == NULL) 
    {
      return 0;
    }
    
    if(node->left == NULL && node->right == NULL) 
    {
      return 1;
    }

    int lH = is_balanced(node->left);
    int rH = is_balanced(node->right);
    
    if(lH == -1 || rH == -1 || abs(lH - rH) > 1) 
    {
      return -1;
    }

    return max(lH, rH) + 1;
}
  

int main()  
{  
    Node* root = nullptr;
    /* Binary tree:
              16
            /   \
           /     \
          10      25
         /  \    /  \
        /    \  /    \
       7    15 18     30

    */

    root = new Node(16);
    root->left = new Node(10);
    root->right = new Node(25);
    root->left->left = new Node(7);
    root->left->right = new Node(15);
    root->right->left = new Node(18);
    root->right->right = new Node(30);

    if (is_balanced(root))
    {
        cout<<"Binary tree is a balanced tree"<<endl;
    } else {
        cout<<"Binary tree is NOT a balanced tree"<<endl;
  
    }




    return 0;  
}  

 

输出:

Binary tree is a balanced tree
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的



      <form id="OXojmaT" class="OSFO10s"><wbr id="I41SqHm"></wbr></form>

      <code class="QR7ylMA"><samp id="g0NCIgD" class="g5CrQr2"></samp></code>


    1. <footer class="dg6yb4Z"></footer>

        <hr id="b67twsP" class="bAyARl5"><form id="x15SWBK" class="xY5uhj8"><hr id="wZSWuNl"></hr></form></hr>




      • <big id="vJS84vy"><rt class="hVzAuKj"></rt></big>

        <kbd id="lZkp5mt" class="lGd333Y"></kbd>

        <meter class="gU47Omi"><rt class="eoBV85K"></rt></meter>