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;
        }*/
    }
  • 相关阅读:
    前端的一些工具
    ubuntu安装intelij idea 和pycharm
    广义欧几里得算法,求解形如ax+by=c的整数解
    Kali安装jdk8
    ARP 项添加失败: 拒绝访问
    Python扩展包,解决”unable to find vcvarsall.bat“
    python实现mschap2
    Ubuntu 安装 Corsaro v2.0.0 全过程
    使用GridFS上传下载图片以及其他文件
    Eclipse设置工作空间编码
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4666029.html
Copyright © 2011-2022 走看看