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;

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    js正则表达式中的问号使用技巧总结
    380. Insert Delete GetRandom O(1)
    34. Find First and Last Position of Element in Sorted Array
    162. Find Peak Element
    220. Contains Duplicate III
    269. Alien Dictionary
    18. 4Sum
    15. 3Sum
    224. Basic Calculator
    227. Basic Calculator II
  • 原文地址:https://www.cnblogs.com/laydown/p/12952948.html
Copyright © 2011-2022 走看看