• 判断是否是平衡二叉树(左子树与右子树高度不大于1)


    package com.hzins.suanfa;
    /**
     * 判断是否是平衡二叉树(左子树与右子树高度不大于1)
     * 
     * @author Administrator
     *
     */
    public class BalancedTree {
        /**
         * level一开始必须为0 当head到递归栈底时,发现自己是null,此时算层数,得从上面算,(自己是null,不算)
         * @param head
         * @param level
         * @return
         */
        public static int getHeight(Node head, int level){
            if(head == null){
                return level;
            }
            int lh = getHeight(head.left, level + 1);
            int rh = getHeight(head.right, level + 1);
            if(lh == -1 || rh == -1 || Math.abs(lh - rh) > -1){
                return -1;
            }
            return Math.max(lh, rh);
        }
        public static boolean isBalance(Node head){
            return getHeight(head, 0) != -1;
        }
        public static void main(String[] args) {
            Node node = new Node(1);
            Node node1 = new Node(2);
            Node node2 = new Node(3);
            Node node3 = new Node(4);
            Node node4 = new Node(5);
            Node node5 = new Node(6);
            Node node6 = new Node(7);
            node.left = node1;
            node.right = node2;
            node1.left = node3;
            node1.right = node4;
            node2.left = node5;
            node2.right = node6;
            System.out.println(isBalance(node));
        }
    }
  • 相关阅读:
    Linux基础命令-cp
    Linux基础命令-mkdir
    Linux基础命令-touch
    Linux基础命令-diff
    Linux基础命令-cut
    Linux基础命令-stat
    System.Web.HttpException: 请求在此上下文中不可用
    数据库日志删除、压缩操作
    如何收缩和删除SQL日志文件
    Excel 常用宏代码大全
  • 原文地址:https://www.cnblogs.com/caobojia/p/6767157.html
Copyright © 2020-2023  润新知