算法系列——Balanced Binary Tree

来源:互联网 发布:java iterator原理 编辑:程序博客网 时间:2024/06/14 05:19

题目描述

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

解题思路

平衡二叉树(Self-balancing binary search tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

据二叉平衡树的定义,我们先写一个求二叉树最大深度的函数depth()。在主函数中,利用比较左右子树depth的差值来判断当前结点的平衡性,如果不满足则返回false。然后递归当前结点的左右子树,得到结果。

程序实现

public class Solution {    public boolean isBalanced(TreeNode root) {    if(root==null){        return true;    }    if(Math.abs(depth(root.left)-depth(root.right))>1)        return false;    return isBalanced(root.left)&&isBalanced(root.right);    }    private int depth(TreeNode node){        if(node==null)            return 0;        return Math.max(depth(node.left),depth(node.right))+1;    }}