LeetCode Balanced Binary Tree

所属专题架构实践
核心标签LeetCode
代码 / 阅读6 min
累计阅读实时统计
TL;DR · 核心摘要

Problem Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary...

Problem

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。

Java 实现

Java· 61 行

package com.coderli.leetcode.algorithms.easy;

/**
 * Given a binary tree, determine if it is height-balanced.
 * <p>
 * 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.
 *
 * @author OneCoder 2017-11-23 22:05
 */
public class BalancedBinaryTree {

    public static void main(String[] args) {
        BalancedBinaryTree balancedBinaryTree = new BalancedBinaryTree();
        TreeNode tree = balancedBinaryTree.new TreeNode(1);
        TreeNode subNodeLeft = balancedBinaryTree.new TreeNode(2);
        TreeNode subNodeRight = balancedBinaryTree.new TreeNode(2);
        subNodeLeft.left = balancedBinaryTree.new TreeNode(3);
        subNodeLeft.right = balancedBinaryTree.new TreeNode(4);
        subNodeRight.left = balancedBinaryTree.new TreeNode(4);
        subNodeRight.right = balancedBinaryTree.new TreeNode(3);
        tree.left = subNodeLeft;
        tree.right = subNodeRight;
        System.out.println(balancedBinaryTree.isBalanced(tree));
    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftSubTreeHeight = treeHeight(root.left);
        int rightSubTreeHeight = treeHeight(root.right);
        int differ = leftSubTreeHeight - rightSubTreeHeight;
        if ( differ > 1 || differ < -1) {
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

    private int treeHeight(TreeNode tree) {
        if (tree == null) {
            return 0;
        }
        int leftSubHeight = treeHeight(tree.left);
        int rightSubHeight = treeHeight(tree.right);
        return leftSubHeight >= rightSubHeight ? leftSubHeight + 1: rightSubHeight + 1;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}

分析

还是递归处理。一个递归计算高度。另一个递归计算每个节点的高度,并进行判断。

OneCoder 信奥远征平台 · oi.coderli.com

看完题解,马上用 240 关实战检验掌握度

覆盖 GESP 1~8 级考纲心法、CSP-J 双栏阅读程序、错题动态变式推演与 90/120 分钟全真模考。

立即闯关
开源代码与考纲字典

配套题解代码归档于 yummy-code 仓库,完整知识点索引见 GESP Wiki。

技术交流与考级答疑

欢迎加入 C++ GESP/CSP 群(688906745) 或 Java/Python 群(982860385)。

同专栏相关推荐

OneCoder

OneCoder

始于 2012

持续记录 C++ GESP/CSP 信奥算法、Java 服务端架构与 Python 工程实战。官方唯一域名:coderli.com

读者讨论与留言

共 0 条讨论
邮箱仅用于接收回复通知,不对外展示
还没有读者留言,欢迎写下你的第一条交流笔记。