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);
        }
    }
  • 相关阅读:
    从苹果系统InstallESD.dmg里提取IOS
    Swift编程语言中文版教程---《The Swift Programming Language》
    VMware workstation 10.0的永久key
    VMware Workstation与Hyper-V不兼容。请先从系统中移除Hyper-V角色,然后再运行VMware Workstation。
    Unity3D游戏制作入门教程
    MyEclipse中文网
    机器学习中的两个概率模型
    机器学习中的两个概率模型
    EM算法概念
    EM算法概念
  • 原文地址:https://www.cnblogs.com/chrischennx/p/4020722.html
Copyright © 2011-2022 走看看