LeetCode-110. Balanced Binary Tree

Description

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.

Example 1

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7
Return true.

Example 2

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
Return false.

Solution 1(C++)

class Solution {
public:  
    int getHight(TreeNode* node){
        if(!node) return 0;
        return max(getHight(node->left), getHight(node->right))+1;
    }
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        return (abs(getHight(root->left)-getHight(root->right))<2) && isBalanced(root->right) && isBalanced(root->left);
    }
};

算法分析

两个点,一,如何求一个树的深度;二,如何判断树是否平衡。

对于树,最好采用迭代的方法来思考,将一个根节点的问题转换成子节点的问题,所以,这样求一个树的深度,其实就是求根节点到若干叶子节点的最大距离。那么当前根节点的深度其实就等于左右子树的两个深度值中,较大的一个加一。非常简单的函数,这应该是条件反射式的基本功。

注意这里判断树是否平衡的问题,在解决了一的问题,我们只能判断这个节点的左右两个子树深度相差不超过1,但是一个平衡二叉树是每个节点,注意,每个节点的左右子树深度相差都不超过1。所以也要用迭代。

程序分析

求当前结点的深度:

int getHight(TreeNode* node){
    if(!node) return 0;
    return max(getHight(node->right), getHeight(node->left))+1;
}

这个应该是基本功的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值