LeetCode刷题笔记(Balanced Binary Tree)

这个题标注的是“Easy”,但事实上并不Easy,下面就和大家分享一下经验吧!

题目如下:

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.

题意分析:

给定一个二叉树,判断其是否是高度平衡二叉树。高度平衡二叉树定义:每一个结点的两个子树的深度差不能超过1。

方法一(递归法)

首先需要定义一个求各节点的两个子树深度函数getDepth,然后对各节点两个子树的深度进行比较,若深度差超过1则不是高度平衡二叉树,即返回false,否则返回true。

解题代码如下:

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

提交后的结果如下:

方法二(方法一优化)

很显然方法一不是很高效,因为每一个节点都需要计算完左右子树深度,再进行判断,其实如果一旦发现左右子树不平衡,则这棵树的平衡性就被破坏了,故不计算其具体的深度了,而只用直接返回-1即可。于是新的解法如下:先定义一个函数getDepth,通过该函数对每个节点进行递归调用并获得左右子树的深度,此过程中若子树是平衡的则返回真实的深度,若不平衡则直接返回-1。

解题代码如下:

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        if (getDepth(root) == -1) 
            return false;
        else 
            return true;
    }
    int getDepth(TreeNode *root) {
        if (!root) return 0;
        int leftDepth = getDepth(root->left);
        if (leftDepth == -1) return -1;
        int rightDepth = getDepth(root->right);
        if (rightDepth == -1) return -1;
        if (abs(leftDepth - rightDepth) > 1) return -1;
        else return max(leftDepth, rightDepth) + 1;
    }
};

提交后的结果如下:

 

 

 

日积月累,与君共进,增增小结,未完待续。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值