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);
        }
  • 相关阅读:
    POJ2635-The Embarrassed Cryptographer-大整数素因子
    poj2115-C Looooops -线性同余方程
    POJ1942-Paths On a Grid-组合数学
    poj1850-CODE-组合
    POJ1019-Number Sequence-数数。。
    CF-Contest339-614
    POJ3252-RoundNumbers-排列组合
    睡前小dp-poj3254-状压dp入门
    AC自动机-HDU3065-简单题
    python学习笔记 day32 实现网盘上传下载功能
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4356983.html
Copyright © 2011-2022 走看看