美文网首页
判断一棵树是否为平衡二叉树

判断一棵树是否为平衡二叉树

作者: lintong | 来源:发表于2015-02-28 14:07 被阅读156次

Consider a height-balancing scheme where following conditions should be checked to determine if a binary tree is balanced.
An empty tree is height-balanced. A non-empty binary tree T is balanced if:

  1. Left subtree of T is balanced
  2. Right subtree of T is balanced
  3. The difference between heights of left subtree and right subtree is not more than 1.
/* Returns true if binary tree with root as root is height-balanced */
bool isBalanced(struct node *root)
{
   int lh; /* for height of left subtree */
   int rh; /* for height of right subtree */ 
 
   /* If tree is empty then return true */
   if(root == NULL)
    return 1;
 
   /* Get the height of left and right sub trees */
   lh = height(root->left);
   rh = height(root->right);
 
   if( abs(lh-rh) <= 1 &&
       isBalanced(root->left) &&
       isBalanced(root->right))
     return 1;
 
   /* If we reach here then tree is not height-balanced */
   return 0;
}
  
/*  The function Compute the "height" of a tree. Height is the
    number of nodes along the longest path from the root node
    down to the farthest leaf node.*/
int height(struct node* node)
{
   /* base case tree is empty */
   if(node == NULL)
       return 0;
 
   /* If tree is not empty then height = 1 + max of left
      height and right heights */
   return 1 + max(height(node->left), height(node->right));
} 

相关文章

  • 1 二叉树的最近公共祖先(leetcode 236) 2 判断是否为平衡二叉树 3 判断二叉树是否为满二叉树 4 ...

  • 链表和二叉树

    单向链表 链表反转 二叉树定义 1、递归中序遍历 2、迭代中序遍历 3、二叉树层序遍历 4、判断一棵树是否为平衡树...

  • swift 二叉树

    二叉树 创建二叉查找树 前序 中序 后序 遍历(递归/非递归) 深度 判断是否为二叉平衡树 判断是否为二叉平衡树 ...

  • Balanced Binary Tree

    Easy 给定二叉树,判断其是否为平衡树。 Solution: 什么是平衡树? 空树平衡,非空二叉树满足下面条件时...

  • Leetcode题解 - Easy - 4

    110- 平衡二叉树 问题 给定一个二叉树,判断它是否是高度平衡的二叉树。 本题中,一棵高度平衡二叉树定义为: 一...

  • 判断一个树是否是BST 求一棵平衡二叉树的最小深度 判断一棵二叉树是否高度平衡

  • 关于二叉树的算法题

    前序遍历中序遍历后序遍历判断是否是平衡二叉树判断是否是对称二叉树判断二叉树高度按照层遍历二叉树判断二叉树宽度

  • Leetcode 110 平衡二叉树

    平衡二叉树 题目 给定一个二叉树,判断它是否是高度平衡的二叉树。 本题中,一棵高度平衡二叉树定义为: 一个二叉树每...

  • 二叉树2-平衡二叉树、完全二叉树、二叉树剪枝

    110.平衡二叉树 给定一个二叉树,判断它是否是高度平衡的二叉树。 一棵高度平衡二叉树定义为:一个二叉树每个节点 ...

  • LeetCode 力扣 110. 平衡二叉树

    题目描述(简单难度) 判断一棵树是否是平衡二叉树,平衡二叉树定义如下: 它是一棵空树或它的左右两个子树的高度差的绝...

网友评论

      本文标题:判断一棵树是否为平衡二叉树

      本文链接:https://www.haomeiwen.com/subject/rwwpxttx.html