Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Have you met this question in a real interview?  
Yes
Example

Given binary tree A={3,9,20,#,#,15,7}, B={3,#,20,15,7}

A)  3            B)    3 
   / \                  \
  9  20                 20
    /  \                / \
   15   7              15  7

The binary tree A is a height-balanced binary tree, but B is not.

这道题有两种比较典型的方法,都是递归的实现;第一种方法是每次先判断根节点是不是平衡的,然后再依次判断左右子树是不是平衡的,这样的实现,会重复计算子节点的高度;第二种方法就是边判断,边记录节点高度,先判断子树是否平衡,然后再判断根节点是否平衡,这种自底而上的方法在很多的树的相关题目中可以减少很多重复的计算(在求最近共同双亲的时候就用到了次思路);

第一种方法:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    int GetHeight(TreeNode *root)
    {
        if(root == NULL)
            return 0;
        return max(GetHeight(root->left), GetHeight(root->right)) + 1;
    }
    bool isBalanced(TreeNode *root) {
        // write your code here
        if(root == NULL)
            return true;
        int lh = GetHeight(root->left);
        int rh = GetHeight(root->right);
        if(abs(lh - rh) > 1)
            return false;
        return isBalanced(root->left) && isBalanced(root->right);
    }
};

第二种方法:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    bool isBalanced(TreeNode *root, int &height){
        if(root == NULL)
            return true;
        int left = 0, right = 0;
        if(!isBalanced(root->left, left)) return false;
        if(!isBalanced(root->right, right)) return false;
        if(abs(left - right) > 1) return false;
        height = max(left, right) + 1;
        return true;
    }
    bool isBalanced(TreeNode *root) {
        // write your code here
        int height = 0;
        return isBalanced(root, height);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值