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.

    题目 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;
        }
    }
  • 相关阅读:
    js replace替换 忽略大小写问题
    Spring security实现国际化问题
    Mac 的mysql5.7没有配置文件,如何解决only_full_group_by 问题
    java设计模式学习
    synchronized的锁问题
    理解java的三种代理模式
    [acm]HDOJ 2059 龟兔赛跑
    [acm]HDOJ 2673 shǎ崽 OrOrOrOrz
    [acm]HDOJ 1200 To and Fro
    [acm]HDOJ 2064 汉诺塔III
  • 原文地址:https://www.cnblogs.com/pku-min/p/4210260.html
Copyright © 2011-2022 走看看