剑指Offer_39_平衡二叉树

题目描述

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

解题思路

递归判断子树是否是平衡二叉树,每次还需要返回子树的高度用以判断当前树是否是平衡的。

实现

public class Solution {
    private class Result{
        boolean isBalanced = false;
        int depth = 0;

        public Result(boolean isBalanced, int depth){
            this.isBalanced = isBalanced;
            this.depth = depth;
        }
    }

    public boolean IsBalanced_Solution(TreeNode root) {
        Result result = isBalanced(root);
        return result.isBalanced;
    }

    private Result isBalanced(TreeNode root) {
        if (root == null) return new Result(true, 0);
        Result left = isBalanced(root.left);
        Result right = isBalanced(root.right);

        int depth = left.depth > right.depth ? left.depth + 1 : right.depth + 1;

        if (!left.isBalanced || !right.isBalanced){
            return new Result(false,depth);
        }

        if (left.depth - right.depth > 1 || right.depth - left.depth > 1){
            return new Result(false,depth);
        }else {
            return new Result(true,depth);
        }
    }
}
posted @ 2016-08-22 10:00  峰扬迪  阅读(113)  评论(0编辑  收藏  举报