• 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;
        }
    }
  • 相关阅读:
    数组子数组求最大值1
    乐游 游戏论坛开发第二阶段
    软件开发第一天
    团队开发
    解决libpython2.6.so.1.0: cannot open shared object file
    linux卸载Python3
    在Linux上安装Python3.7.1
    Pytest高级进阶之Fixture
    发现使用id定位元操作不了
    报错:Original error: Could not proxy command to remote server. Original error: Error: read ECONNRESET
  • 原文地址:https://www.cnblogs.com/pku-min/p/4210260.html
Copyright © 2020-2023  润新知