【发布时间】:2015-06-13 06:53:44
【问题描述】:
checkIfBalanced() 下面代码中的方法如果树是平衡的则返回 true,否则返回 false。然而,在每次递归中,它都会创建 TreeData 对象。在我看来,空间复杂度是 O(1),因为在弹出每个堆栈帧后,在该堆栈帧上创建的对象的引用会丢失并被垃圾收集。
我对吗 ?
请注意:
我不是在寻找改进/更改我的代码的建议。下面的代码示例是为问我的问题量身定制的。
另外,
please ignore space-complexity adding stack frames。我正在寻找创建的数字“TreeData”对象的空间复杂度。在我看来,任何时候都只有 3 个 TreeData 对象。这就是我要验证的。谢谢。
private static class TreeData {
private int height;
private boolean isBalanced;
TreeData(int height, boolean isBalanced) {
this.height = height;
this.isBalanced = isBalanced;
}
}
public boolean checkIfBalanced() {
if (root == null) {
throw new IllegalStateException();
}
return checkBalanced(root).isBalanced;
}
public TreeData checkBalanced(TreeNode node) {
if (node == null) return new TreeData(-1, true);
TreeData tdLeft = checkBalanced(node.left);
TreeData tdRight = checkBalanced(node.right);
if (tdLeft.isBalanced && tdRight.isBalanced && Math.abs(tdLeft.height - tdRight.height) <= 1) {
return new TreeData(Math.max(tdLeft.height, tdRight.height) + 1, true);
}
return new TreeData(Math.max(tdLeft.height, tdRight.height) + 1, false);
}
【问题讨论】:
标签: algorithm recursion space-complexity