110. 平衡二叉树


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;
 *     }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
         if (root == null) {
            return true;
        } else {
            return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
        &#125;
    &#125;

    public int height(TreeNode root) &#123;
        if (root == null) &#123;
            return 0;
        &#125; else &#123;
            return Math.max(height(root.left), height(root.right)) + 1;
        &#125;
    &#125;

// 作者:LeetCode-Solution
// 链接:https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/

    &#125;
&#125;
/**
 * Definition for a binary tree node.
 * public class TreeNode &#123;
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() &#123;&#125;
 *     TreeNode(int val) &#123; this.val = val; &#125;
 *     TreeNode(int val, TreeNode left, TreeNode right) &#123;
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     &#125;
 * &#125;
 */
class Solution &#123;
    public boolean isBalanced(TreeNode root) &#123;
        return height(root) >= 0;
    &#125;

    public int height(TreeNode root) &#123;
        if (root == null) &#123;
            return 0;
        &#125;
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) &#123;
            return -1;
        &#125; else &#123;
            return Math.max(leftHeight, rightHeight) + 1;
        &#125;
    &#125;

// 作者:LeetCode-Solution
// 链接:https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/

&#125;

文章作者:   future
版权声明:   本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 future !
 上一篇
剑指 Offer 10- I. 斐波那契数列 剑指 Offer 10- I. 斐波那契数列
剑指 Offer 10- I. 斐波那契数列写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项(即 F(N))。斐波那契数列的定义如下:F(0) = 0,   F(1) = 1F(N) = F(N - 1) + F(N
2021-02-26 future
下一篇 
142. 环形链表 II 142. 环形链表 II
142. 环形链表 II给定一个链表,返回链表开始入环的第一个节点。  如果链表无环,则返回  null。 public ListNode detectCycle(ListNode head) &#123; if
2021-02-26 future
  目录