6

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:

  1. I am not looking for suggestions to improve/change my code. The following example of code is tailor made to ask my question.

  2. 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);
    }
JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

3 Answers3

5

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 ?

No, you are wrong in assuming that. Ray Toal has very beautifully explained this. At any point in the recursion, you must count all those internal stack frames which are being saved into memory, as Space-Complexity considers into account all the auxiliary space(extra space) alongwith the input(not emphasised here).

Next,

I am looking for space complexity of number 'TreeData' objects created.

The maximum space consumed by a recursive program is proportional to the maximum depth of the recursion tree framed. The maximum depth of the recursion tree is defined as the length of the longest path in the tree.

For the given program, the program will start from root of the tree, and first start creating the left sub-tree and then checking the right-subtree. Finally, it will return the length of the longest path and whether the tree is balanced OR not.

It looks to me that at any point there would be only 3 TreeData objects. That's what I want to verify.

No, at any particular execution time, first all the left subtrees are verified and then the right-subtrees are verified, so the number of objects of TreeData in the memory would be only 1. It will every time check for it's left OR right child. And, hence, all those (log n --- in case of balanced tree, OR n --- in case of degenerate tree) nodes except one will keep getting stacked in the memory. At a particular moment of time, only 1 TreeData object would be in the active state, others would be paused and stacked in the memory and waiting for their turn to pop out.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
  • so the number of objects of TreeData in the memory would be only 1 - so, if I "ignore stack space" , will complexity be O(1) ? Will those objects be garbage collected if references are popped of stack ? – JavaDeveloper Jun 12 '15 at 23:13
  • @JavaDeveloper- 1. If you ignore stack space, and consider only the current reference, then there will be only 1 active TreeData object. 2. ***Maybe/Maybe not***, as soon as the stack pops out all the nodes, the objects may OR may not be garbage collected, it depends on the JVM to guess whether they are going to be reused in the future. For surity, you need to do that manually by setting those objects to `null` so that they could get garbage collected.Read the answers(especially Stephen C's answer)-->http://stackoverflow.com/questions/27781116/garbage-collection-in-java-with-recursive-function – Am_I_Helpful Jun 12 '15 at 23:24
2

You are not using tail recursion here, and you are building stack frames as you recurse up the tree. To be fair, count those stack frames. If your tree is balanced then you will be making log n stack frames as you recurse. In the worst case, with a fully degenerate tree, you might have up to n stack frames.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
1

However in each recursion it creates TreeData object.

Not true. You only create the new TreeData object at the base case of your recursion. If you're concerned about this, why don't you just have a static final TreeData instance declared once in the class that you can use. After all, the only thing you're propagating back from this Node is it's isBalanced boolean value.

You can also just propagate the boolean value back up directly if you change your method signature to return a boolean.

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124