zoukankan      html  css  js  c++  java
  • 给定一棵二叉树的头节点,判断是不是平衡二叉树


    /**
    * 给定一棵二叉树的头节点,判断是不是平衡二叉树
    */
    public class IsBalancedBT {

    public static boolean isBalancedBT(Node root) {
    if (root == null) {
    return true;
    }
    return process(root).isBalanced;
    }

    private static ResultInfo process(Node node) {
    if (node == null) {
    return new ResultInfo(0, true);
    }
    ResultInfo leftResult = process(node.left);
    ResultInfo rightResult = process(node.right);
    int height = Math.max(leftResult.height, rightResult.height) + 1;
    boolean isBalanced = true;
    if (!leftResult.isBalanced || !rightResult.isBalanced || Math.abs(leftResult.height - rightResult.height) > 1) {
    isBalanced = false;
    }
    return new ResultInfo(height, isBalanced);
    }

    /**
    * 向左右子树索要信息
    */
    public static class ResultInfo {

    // 当前高度
    public int height;

    // 是否平衡
    public boolean isBalanced;

    public ResultInfo(int height, boolean isBalanced) {
    this.height = height;
    this.isBalanced = isBalanced;
    }

    }

    /**
    * 二叉树结构
    */
    public static class Node {

    public Node left;

    public Node right;

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    工厂方法模式
    代理模式
    观察者模式
    策略模式
    单例模式
    简单工厂模式
    lintcode:等价二叉树
    lintcode:被围绕的区域
    lintcode:二叉树的所有路径
    lintcode:快乐数
  • 原文地址:https://www.cnblogs.com/laydown/p/12952948.html
Copyright © 2011-2022 走看看