检查二叉树是否平衡(Big-O)

时间:2013-01-30 03:29:05

标签: binary-tree big-o

检查二叉树是否平衡。

CTCI第五届的源代码:

public class QuestionBrute {

public static int getHeight(TreeNode root) {
    if (root == null) {
        return 0;
    }
    return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}

public static boolean isBalanced(TreeNode root) {
    if (root == null) {
        return true;
    }
    int heightDiff = getHeight(root.left) - getHeight(root.right);
    if (Math.abs(heightDiff) > 1) {
        return false;
    }
    else {
        return isBalanced(root.left) && isBalanced(root.right);
    }
}

public static void main(String[] args) {
    // Create balanced tree
    int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    TreeNode root = TreeNode.createMinimalBST(array);
    System.out.println("Root? " + root.data);
    System.out.println("Is balanced? " + isBalanced(root));

    // Could be balanced, actually, but it's very unlikely...
    TreeNode unbalanced = new TreeNode(10);
    for (int i = 0; i < 10; i++) {
        unbalanced.insertInOrder(AssortedMethods.randomIntInRange(0, 100));
    }
    System.out.println("Root? " + unbalanced.data);
    System.out.println("Is balanced? " + isBalanced(unbalanced));
}
}

由于算法必须检查每个节点的高度,并且我们不在每次递归中保存高度,因此运行时间应为O(N ^ 2)。

1 个答案:

答案 0 :(得分:3)

首先让我们修复一下你的代码。检查根是否平衡的功能将无法正常工作,因为在以下情况下二进制树是平衡的:

maxHeight(root) - minHeight(root) <= 1

我引用维基百科:“平衡二叉树通常被定义为二叉树,其中每个节点的两个子树的深度相差1或更小”

您的算法将为此树提供错误的答案:

A simple binary tree of size 9 and height 3, with a root node whose value is 2. The above tree is unbalanced and not sorted.

当您致电getHeight(Node7)时,它将返回3,当您致电getHeight(Node5)时,它也会返回3,自(0>1) == false后您将返回true :(

要解决此问题,您只需按照与int MinHeight(TreeNode node)相同的方式实施getHeight(),但Math.min()

现在回答你的问题。就运行时复杂性而言,每当从根调用getHeight()函数时,您正在执行DFS,并且由于必须访问所有节点以查找树的高度,因此该算法将为O(N )。现在,当您调用maxHeight(root)minHeight(root)时,执行此算法两次都是正确的,但因为它们都是O(N)(假设它们与getHeight()完全相同)整体复杂性将C * N作为某些常数C的上限,并且所有N大于某些N结,即O(N),其中N是树的节点数;)

干杯!