Leetcode110. 平衡二叉树

110. 平衡二叉树

Difficulty: 简单

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

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

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

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:true

示例 2:

输入:root = [1,2,2,3,3,null,null,4,4]
输出:false

示例 3:

输入:root = []
输出:true

提示:

  • 树中的节点数在范围 [0, 5000]
  • -10<sup>4</sup> <= Node.val <= 10<sup>4</sup>

Solution

Language: java

​/**
 * 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) {
        return postOrder(root).isBalanced;
    }

    private Twotuple postOrder(TreeNode root){
        if(root == null) return new Twotuple(0, true);
        Twotuple left = postOrder(root.left);
        if(!left.isBalanced) return new Twotuple(0, false);
        Twotuple right = postOrder(root.right);
        if(!right.isBalanced) return new Twotuple(0, false);
        if(Math.abs(left.heigh - right.heigh) > 1) return new Twotuple(0, false);
        return new Twotuple(Math.max(left.heigh, right.heigh) + 1, true);
    }
    class Twotuple{
        int heigh;
        boolean isBalanced;
        public Twotuple(int h, boolean b){
            this.heigh = h;
            this.isBalanced = b;
        }
    }
}
原文地址:https://www.cnblogs.com/liuyongyu/p/14329065.html