程序员面试金典-面试题 04.04. 检查平衡性

题目:

https://leetcode-cn.com/problems/check-balance-lcci/

实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。


示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/
9 20
/
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/
2 2
/
3 3
/
4 4
返回 false 。

分析:

写一个求当前结点为根节点的树的高度的函数,当该节点左右子树高度差大于1时,返回-1,否则返回左右子树最大高度加1,递归求解左右孩子。当最后返回值为-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) {
        if(height(root) == -1)
            return false;
        return true;
    }
    private int height(TreeNode root){
        if(root == null)
            return 0;
        int l = height(root.left);
        int r = height(root.right);
        if(l == -1 || r == -1)
            return -1;
        if(Math.abs(l - r) > 1)
            return -1;
        return Math.max(l, r) + 1;
    }
}
原文地址:https://www.cnblogs.com/silentteller/p/12426912.html