Leetcode 110. Balanced Binary Tree

题目链接:https://leetcode.cn/problems/balanced-binary-tree/

/**
 * 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;
        return getHeght(root) == -1 ? false : true;
    }
    public int getHeght(TreeNode node){
        if (node == null) return 0;
        int l = getHeght(node.left);
        if (l == -1) return -1;
        int r = getHeght(node.right);
        if (r == -1) return -1;
        else return Math.abs(l - r) > 1 ? -1 : 1 + Math.max(l, r);
    }
}

你可能感兴趣的:(算法打卡,leetcode,算法,职场和发展)