首页 > 编程语言 > 详细

java 递归实现平衡二叉树

时间:2017-05-28 12:09:42      阅读:280      评论:0      收藏:0      [点我收藏+]

public class 平衡二叉树
{
    public class TreeNode
    {
        TreeNode left;
        TreeNode right;
        int val;

        TreeNode(int x)
        {
            this.val = x;
        }
    }

    // 获取深度
    private int getDepth(TreeNode tree, int currentDepth)
    {
        if (tree == null)
        {
            return currentDepth;
        }
        return Math.max(getDepth(tree.left, currentDepth + 1),
                getDepth(tree.right, currentDepth + 1));

    }

    // 采用递归解决
    public boolean isBalanced(TreeNode root)
    {
        if (root == null)
        {
            return true;
        }
        int depthOfLeft = getDepth(root.left, 1);
        int depthOfRight = getDepth(root.right, 1);
        if (Math.abs(depthOfLeft - depthOfRight) > 1)
        {
            return false;
        }
        else
        {
            return isBalanced(root.left) && isBalanced(root.right);
        }
    }
}

java 递归实现平衡二叉树

原文:http://www.cnblogs.com/qingtianBKY/p/6915417.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!