平衡二叉树

来源:互联网 发布:华南师范大学网络自助 编辑:程序博客网 时间:2024/06/14 10:20

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

结合之前的求二叉树的高度的方法,得到以下递归解法:

public class Solution {    public boolean IsBalanced_Solution(TreeNode root) {        if(root == null) return true;        int h1 = depth(root.left);        int h2 = depth(root.right);        return Math.abs(h1-h2) < 2 && IsBalanced_Solution(root.left) &&            IsBalanced_Solution(root.right);    }    public int depth(TreeNode root){        if(root == null) return 0;        int h1 = depth(root.left);        int h2 = depth(root.right);        return 1 + Math.max(h1, h2);    }}
0 0
原创粉丝点击