java - 如何修复决定树是否平衡树的方法?

标签 java avl-tree

例如,我有一棵树:

                              8
                            _   _
                           /     \ 
                         1       48
                        /       /  \
                       0       40   50
                              /
                             10

当我向 TREE 添加 10 时,我的方法确定该 AVL 树不是 AVL 树,并尝试平衡它。我不明白为什么 isAVLTree 方法不起作用。

public static boolean isAVLTree(Root root) {
        return (findMaxDepth(root) - findMinDepth(root)) <= 1;
    }
public static int findMaxDepth(Root root) {
        if (root == null ) {
            return 0;
        }
        return 1 + Math.max(findMaxDepth(root.leftSide), findMaxDepth(root.rightSide));
    }

 public static int findMinDepth(Root root) {
        if (root == null) {
            return 0;
        }
        return 1 + Math.min(findMinDepth(root.leftSide), findMinDepth(root.rightSide));
}

目前方法isAVLTree返回false,因为

(findMaxDepth(root) - findMinDepth(root)) <= 1
((         4        -        2)           <= 1 )   ->>>>>>>>>>>>>> FALSE

最佳答案

In an AVL tree, the heights of the two child subtrees of any node differ by at most one

( AVL Tree )

这不是您在 isAVLTree 方法中实现的。最大深度和最小深度之间的差异不必 <= 1。

相反,你应该要求左右子树都是AVL树,并且左右子树的高度差<= 1。

public static boolean isAVLTree(Root root) 
{
    if (root == null) {
        return true;
    }

    return Math.abs(findMaxDepth(root.leftSide) - findMaxDepth(root.rightSide)) <= 1 &&
        isAVLTree (root.rightSide) &&
        isAVLTree (root.leftSide);
}

关于java - 如何修复决定树是否平衡树的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57744913/

相关文章:

java - java中没有main方法和变量的程序

java - AndroidManifest 文件的问题

c - AVL树,struct中的访问指针

java - AVL树toString()的实现

java - 从 Jetty HTTPServletRequest 获取 MAC 地址

java - 自动化 webstart 过程

c++ - AVL Tree Rotation 的正确实现是什么?

algorithm - 家庭作业帮助 - AVL 树

java - 从命令行传递 Maven 编译器选项

algorithm - 红黑树的插入和删除速度如何比AVL树更快?