• 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.

    题目 Balanced Binary Tree
    通过率 32.1%
    难度 Easy

    题目是判断是否是平衡二叉树

    平衡二叉树定义(AVL):它或者是一颗空树,或者具有以下性质的二叉树:它的左子树和右子树的深度之差的绝对值不超过1,且它的左子树和右子树都是一颗平衡二叉树。

    关键点:深度优先遍历、递归;

    我们的判断过程从定义入手即可:

     1. 若为空树,则为true;

     2. 若不为空树,调用getHeight()方法,若为二叉树此方法返回的是树的高度,否则返回-1;

     3. 在getHeight()方法中,利用递归的思想处理左右子树;

    java代码:

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root==null) return true;
            if(getHeight(root) == -1) return false;
            return true;
        }
        
        public int getHeight(TreeNode root){
            if(root == null) return 0;
            
            int left = getHeight(root.left);
            int right = getHeight(root.right);
            if(left==-1 || right==-1) return -1;
            if(Math.abs(left-right)>1) return -1;
            return Math.max(left,right)+1;
        }
    }
  • 相关阅读:
    msyql 授权ip
    discuz和ecmail最简单解决同步登陆登出
    mysqldump大数据的备份与恢复
    PHP-OB缓存
    jquery对象和dom对象
    Javascript面向对象编程-深入浅出讲的非常棒
    修改mysql密码
    phpcms 详情页没有点击数的问题
    phpcms pc标签调用整理
    设置devenv.exe启动版本(转)
  • 原文地址:https://www.cnblogs.com/pku-min/p/4210260.html
Copyright © 2020-2023  润新知