【Leetcode】110. 平衡二叉树

111 阅读1分钟

题目描述

在这里插入图片描述

// 110. 平衡二叉树

// 给定一个二叉树,判断它是否是高度平衡的二叉树。

// 本题中,一棵高度平衡二叉树定义为:
// 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。


题解

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */


// 本题和【剑指offer】55.2 平衡二叉树 一模一样
// 
// 执行用时:88 ms, 在所有 Java 提交中击败了5.18%的用户
// 内存消耗:39.1 MB, 在所有 Java 提交中击败了5.07%的用户
class Solution {
    public boolean res = true;

    public boolean isBalanced(TreeNode root) {
        if (root == null)
            return res;
        preOrder(root);
        return res;
    }

    private void preOrder(TreeNode root) {
        if (root == null)
            return;
        if (Math.abs(searchDepth(root.left) - searchDepth(root.right)) > 1)
            res = false;			
        preOrder(root.left);
        preOrder(root.right);
    }

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


// 优化一下
// 执行用时:1 ms, 在所有 Java 提交中击败了99.99%的用户
// 内存消耗:38.3 MB, 在所有 Java 提交中击败了84.48%的用户

class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null)
            return true;
        if (Math.abs(depth(root.left) - depth(root.right)) > 1) {
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

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