剑指offer---平衡二叉树

来源:互联网 发布:lol国服mac版本几时出 编辑:程序博客网 时间:2024/06/05 03:26

输入一棵二叉树,判断该二叉树是否是平衡二叉树

import java.lang.Math;class ResultType {    boolean isBST;    int deepth;    public ResultType(boolean isBST, int deepth) {        this.isBST = isBST;        this.deepth = deepth;    }}public class Solution {    public boolean IsBalanced_Solution(TreeNode root) {        if (root == null) {            return true;        }        ResultType result = util(root);        return result.isBST;    }    private ResultType util(TreeNode root) {        if (root == null) {            return new ResultType(true, 0);        }        ResultType left = util(root.left);        ResultType right = util(root.right);        if (left.isBST && right.isBST && Math.abs(left.deepth - right.deepth) <= 1) {            return new ResultType(true, Math.max(left.deepth, right.deepth) + 1);        }        return new ResultType(false, -1);    }}