LeetCode——Balanced Binary Tree

24 篇文章 0 订阅
17 篇文章 0 订阅
LeetCode——Balanced Binary Tree

#110

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.

这一题的目的是判断一棵二叉树是否是平衡二叉树,即两个子树的中每个节点的深度差不超过1。思路是这样的,分别求出各个节点的深度,然后对左右子树的最大深度进行比较。这里就可以用到前面的求树的最大深度的函数,再利用一个递归就可以完成功能。

  • C++
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
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 1 + max(getDepth(root->left), getDepth(root->right));
    }
};

这个解法是很容易想出来的,然后我看了一些其他的优化的答案。一点见解。一种解法的优化,最主要的核心是不变的,比如递归的话,递归核心是不会变的,能够变得可以是形式,可以是一些结构的优化,比如通过组合。比如这一题的一种优化解法,DFS是不变的,但是在比较过程中,进行了简化,不要求每个节点的深度,如果递归到子树是不平衡的,直接返回-1,如果子树平衡,则返回深度。

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

其实就是在递归过程中从下到上的过程中,将左右子树进行了一次比较,而不是全部传到上面,进行总的一次比较,所以时间复杂度会降低,相当于是线性的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值