zoukankan      html  css  js  c++  java
  • LeetCode——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.

    分析:

    判断平衡二叉树,第一想法肯定是求出左右子树的深度,看是否相差大于1,但马上发现这是一个递归过程,每次递归返回的是深度,可是还得判断是否平衡,如果不平衡如何返回是否平衡,

    然后你可能会想到使用两个函数,一个函数用于递归求深度,一个函数用于递归求是否平衡,如下:

    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        int l=depth(root.left);
        int r=depth(root.right);
        return ((int)Math.abs(l-r)<2)&&isBalanced(root.left) && isBalanced(root.right);
    }
    static int depth(TreeNode n){
            if(n==null) return 0;
            return Math.max(depth(n.left),depth(n.right))+1;
       }

    再然后你会发现时间复杂度为O(n^2),做了很多的无用功。

    要想降低时间复杂度,就得想一个办法让我们在递归求深度的同时判断是否是平衡二叉树,也就是还是得解决求深度的时候递归返回值的问题,在LeetCode中discuss了一下大笑,然后发现了大神们用了一个求深度时不可能出现的值轻松解决问题,关键代码如下:

    public final int UNB = -99;
    public int balanceJudge(TreeNode root){
            if(root==null)return 0;
            int l = balanceJudge(root.left);
            int r = balanceJudge(root.right);
            if(l==UNB || r== UNB || Math.abs(l-r)>1) return UNB;
            return 1+(l>r?l:r);
        }

    最后只需要判定返回值否为UNB就可以知道改二叉树是否平衡了。。


    完整代码如下(java):

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public final int UNB = -99;
        public boolean isBalanced(TreeNode root) {
            int result = balanceJudge(root);
            if(result != UNB)return true;
            else return false;
        }
        
        public int balanceJudge(TreeNode root){
            if(root==null)return 0;
            int l = balanceJudge(root.left);
            int r = balanceJudge(root.right);
            if(l==UNB || r== UNB || Math.abs(l-r)>1) return UNB;
            return 1+(l>r?l:r);
        }
    }
  • 相关阅读:
    paper 113:Bhattacharyya distance
    (ZT)算法杂货铺——分类算法之朴素贝叶斯分类(Naive Bayesian classification)
    (ZT)算法杂货铺——分类算法之贝叶斯网络(Bayesian networks)
    (ZT)算法杂货铺——分类算法之决策树(Decision tree)
    (ZT)算法杂货铺——k均值聚类(K-means)
    超详细的遗传算法(Genetic Algorithm)解析
    Ontology理论研究和应用建模
    观察者模式(Observer)和发布(Publish/订阅模式(Subscribe)的区别
    程序员常用字体(vs2008字体修改方案)
    雾计算和边缘计算的区别
  • 原文地址:https://www.cnblogs.com/chrischennx/p/4020722.html
Copyright © 2011-2022 走看看