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.

问题分析

判断一棵树是不是平衡二叉树,用递归进行计算最为简便

代码实现

public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        int leftDepth = getTreeDepth(root.left);
        int rightDepth = getTreeDepth(root.right);
        if (Math.abs(leftDepth - rightDepth) <= 1) {
            if (isBalanced(root.left) && isBalanced(root.right)) {
                return true;
            }
        }
        return false;
    }

    private int getTreeDepth(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) return 1;
        return Math.max(getTreeDepth(root.left), getTreeDepth(root.right)) + 1;
    }

你可能感兴趣的:(LeetCode每日一题:判断是不是平衡二叉树)