剑指Offer_39_平衡二叉树

来源:互联网 发布:directx9修复软件64位 编辑:程序博客网 时间:2024/06/09 16:58

题目描述

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

解题思路

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

实现

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);        }    }}
0 0