0

JZ-039-平衡二叉树

 2 years ago
source link: https://segmentfault.com/a/1190000041193844
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JZ-039-平衡二叉树

发布于 12 月 28 日

平衡二叉树

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

  • 在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树

题目链接: 平衡二叉树

/**
 * 标题:平衡二叉树
 * 题目描述
 * 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
 * 在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
 * 题目链接:
 * https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&&tqId=11192&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 */
public class Jz39 {

    private boolean isBalanced = true;

    public boolean isBalanced_Solution(TreeNode root) {
        height(root);
        return isBalanced;
    }

    /**
     * 递归
     *
     * @param root
     * @return
     */
    private int height(TreeNode root) {
        if (root == null || !isBalanced) {
            return 0;
        }
        int left = height(root.left);
        int right = height(root.right);
        if (Math.abs(left - right) > 1) {
            isBalanced = false;
        }
        return 1 + Math.max(left, right);
    }

    public static void main(String[] args) {

    }
}

【每日寄语】 做个内心阳光的人。不忧伤,不心急。坚强、向上,靠近阳光。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK