zoukankan      html  css  js  c++  java
  • Balanced Binary Tree——LeetCode

    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.

    题意:给定一个二叉树,判断是否是高度平衡的,这里的高度平衡定义是每个节点的左右子树的高度差不超过1。

    第一种方式:递归算出每个节点的左右子树的高度,如果相差超过1,直接返回false。

    第二种方式:DFS遍历一遍,遇到左右子树高度差超过1的,记录一个全局变量isBlance为false,最后返回这个boolean的全局变量即可。

    显然,第二种方式更优,只需要从根节点计算一遍即可,而第一种方式有很多重复计算。

    Talk is cheap>>

    第一种方式:

    public class BalancedBinaryTree {
        public boolean isBalanced(TreeNode root) {
            if (root == null)
                return true;
            List<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while (!queue.isEmpty()) {
                TreeNode node = queue.get(0);
                queue.remove(0);
                if (Math.abs(maxDepth(node.left) - maxDepth(node.right)) > 1)
                    return false;
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            return true;
        }
    
        public int maxDepth(TreeNode root) {
            if (root == null)
                return 0;
            int l = maxDepth(root.left);
            int r = maxDepth(root.right);
            return 1 + Math.max(l, r);
        }
    }

    第二种方式:

      private boolean result = true;
    
        public boolean isBalanced(TreeNode root) {
            maxDepth(root);
            return result;
        }
    
        public int maxDepth(TreeNode root) {
            if (root == null)
                return 0;
            int l = maxDepth(root.left);
            int r = maxDepth(root.right);
            if (Math.abs(l - r) > 1)
                result = false;
            return 1 + Math.max(l, r);
        }
  • 相关阅读:
    体温填报APP--流程设计
    构建之法阅读笔记(一)
    家庭记账本(七)
    家庭记账本(六)
    家庭记账本(五)
    家庭记账本(四)
    家庭记账本(三)
    家庭记账本(二)
    家庭记账本(一)
    20210207 BaseAdapter
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4356983.html
Copyright © 2011-2022 走看看