checkIfBalanced()
method in the code below returns true if the tree is balanced and false otherwise. However in each recursion it creates TreeData object. In my opinion space complexity is O(1) as after each stack frame is popped, the reference of the object created on that stack frame is lost and garbage collected.
Am I right ?
Please note:
I am not looking for suggestions to improve/change my code. The following example of code is tailor made to ask my question.
Also,
please ignore space-complexity adding stack frames
. I am looking for space complexity of number 'TreeData' objects created. It looks to me that at any point there would be only 3 TreeData objects. Thats what I want to verify. Thanks.
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);
}