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;
        }
    }
  • 相关阅读:
    如何提高PHP执行效率
    PHP MySQL 预处理语句
    CDN拾遗
    Rendering React components to the document body
    模拟select,隐藏下拉列表的几种实现
    前端数据范式化
    其实我们可以少写点if else和switch
    [译]the cost of javascript in 2018(1)
    provisional headers are shown 知多少
    f5到底刷新了点什么,你知道吗
  • 原文地址:https://www.cnblogs.com/pku-min/p/4210260.html
Copyright © 2011-2022 走看看