zoukankan      html  css  js  c++  java
  • 二叉树平衡-递归

    package JianZhioffer;
    /**
     * 输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
     */
    //思路:1.左子树平衡
    //     2.右子树平衡
    //      3.左右差别最大1
    public class test55II {
        public static void main(String[] args) {
            TreeNode t=new TreeNode(3);
            t.left=new TreeNode(9);
            t.right=new TreeNode(20);
            t.right.left=new TreeNode(15);
            t.right.right=new TreeNode(7);
            System.out.println(isBalanced(t));    
        }
        public static boolean isBalanced(TreeNode root) {
            if(root==null){
                return true;
            }
            if(!isBalanced(root.left)){
                return false;
            }
            if(!isBalanced(root.right)){
                return false;
            }
            int l=helper(root.left);
            int r=helper(root.right);
            if(Math.abs(l-r)>1){
                return false;
            }else{
                return true;
            } 
        }
        public static int helper(TreeNode root){
            if(root==null){
                return 0;
            }
            int left=helper(root.left)+1;
            int right=helper(root.right)+1;
    
            return Math.max(left, right);
        }
        
    }
  • 相关阅读:
    24.Azkaban调度脚本的编写
    Docker 安装 Apache
    Docker 安装 MongoDB
    Docker 安装 Redis
    Docker 安装 Python
    Docker 安装 Tomcat
    Docker 安装 MySQL
    Docker 安装 PHP
    Docker 安装 Nginx
    Docker 镜像使用
  • 原文地址:https://www.cnblogs.com/jieyi/p/14172451.html
Copyright © 2011-2022 走看看