zoukankan      html  css  js  c++  java
  • [leedcode 110] 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.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            //需要构造一个函数求一个节点的高度,然后isBalanced函数每一层开始验证左右字子树是否满足要求,此种思想非常直观
            //这种解法效率不高,因为求每个节点是否满足时,需要求一遍高度再验证,然后再求下一层,中间计算有重复计算
            //另一种优化算法,在求高度时,就能把信息直接返回,不满足的默认直接回-1,不需要再比较
            if(root==null) return true;
            int left=getDepth(root.left);
            int right=getDepth(root.right);
            if(left>right+1||right>left+1) return false;
            else{
                return isBalanced(root.left)&&isBalanced(root.right);
            }
        }
        int getDepth(TreeNode root){
            if(root==null) return 0;
            return Math.max(getDepth(root.left),getDepth(root.right))+1;
            
        }
        
        /* public boolean isBalanced(TreeNode root){
           
           int temp=getDepth(root);
           return temp>-1;
        }
        public int getDepth(TreeNode root){
            if(root==null) return 0;
            int left=getDepth(root.left);
            int right=getDepth(root.right);
            int temp=Math.abs(left-right);
            if(left==-1||right==-1||temp>1) return -1;
            
           return  left>right?left+1:right+1;
        }*/
    }
  • 相关阅读:
    java中通过jacob调用dts进行数据导入导出
    Tomcat6 配置快逸报表
    [转]Sql Server Alter语句
    redhat linux卸载自带的Java1.4.2安装JDK6
    住房公积金额度计算
    JVisualVM使用
    Tomcat假死之问题原因排查
    JVM内存调优之监控篇
    tomcat之JVM GC 日志文件生成
    webstorm8的license
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4666029.html
Copyright © 2011-2022 走看看