【LeetCode】 110. Balanced Binary Tree 平衡二叉树(Easy)(JAVA)

【LeetCode】 110. Balanced Binary Tree 平衡二叉树(Easy)(JAVA)

题目地址: https://leetcode.com/problems/balanced-binary-tree/

题目描述:

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 left and right subtrees of every node differ in height by no more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

题目大意

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

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

解题方法

1、采用递归计算二叉树的高度
2、遇到左右节点高度大于 1 的,直接返回结果

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        int height = height(root);
        return height != -1;
    }

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

执行用时 : 1 ms, 在所有 Java 提交中击败了 99.81% 的用户
内存消耗 : 40.2 MB, 在所有 Java 提交中击败了 17.65% 的用户

你可能感兴趣的:(Leetcode,二叉树,leetcode,java,面试,算法)