LeetCode题解: Balanced Binary Tree

判定一棵二叉树是不是二叉平衡树。

链接:https://oj.leetcode.com/problems/balanced-binary-tree/

题目描述:

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.

给出一棵二叉树,判断它是不是平衡二叉树。
平衡二叉树被定义每个节点的两个子树高度差不超过1。

这道题目比较简单,
一棵树是不是平衡二叉树,可以输入一个结点,计算它的两棵子树的高度差,然后与1比较,递归进行这个操作就可以完成判定。

回顾一下二叉树的概念,平衡二叉树基于二叉查找树(Binary Search Tree)
二叉查找树或者是一棵空树;
或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
二叉查找树是插入,排序,查找的平均时间复杂度都是O(Log(n)),最差情况是O(n),
二叉树的平衡因子是该结点的左子树的深度减去它的右子树的深度,平衡二叉树的BF因子绝对为1。

点击查看 平衡二叉树的构造

下面用Java完成Solution,注意空树的情况。

public class BalancedBinaryTreeSolution {
    /**
     * 访问局部内部类必须先有外部类对象,此处必须用Static修饰
     */
//    public static class TreeNode {
//           int val;
//           TreeNode left;
//           TreeNode right;
//           TreeNode(int x){ val = x;}
//    }
    
    //OJ支持JDK的Math函数
    public boolean isBalanced(TreeNode root) {
        //注意空树的情况
        if(root == null)
            return true;
        
        int leftDepth=getDepth(root.left);
        int rightDepth=getDepth(root.right);
        int altitude=rightDepth-leftDepth;
        //注意只有一个顶点的情况
        if(Math.abs(altitude)>1)
            return false;            
        else
            //递归比较
            return isBalanced(root.left) && isBalanced(root.right);
    }
    
    private int getDepth(TreeNode node){
        if(node == null)
            return 0;
        //递归求深度
        return  1+Math.max(getDepth(node.left), getDepth(node.right));
    }
}

同步: http://www.cnblogs.com/binyue/
发布了29 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/leread/article/details/41870411