space complexity of tree dfs algorithm

Adam :

I am evaluating the space complexity of the following algorithm to invert a tree:

public TreeNode invertTree(TreeNode root) {
    if (root == null) {
        return null;
    }
    TreeNode right = invertTree(root.right);
    TreeNode left = invertTree(root.left);
    root.left = right;
    root.right = left;
    return root;
}

I know that the space complexity is the number of the times that the call stack is called which is O(h) where h is the height of the tree. But my confusion is that at each level of the call stack, we are returning a tree, which takes up some space, why are we not counting this space? I think it is because the tree is passed in by the function. But how do you account for that space? Java is passed by reference, how many space is taken up by the reference at each call stack level?

Joni :

The space needed for an object reference is constant. It does not depend on what you are referencing. The space needed for the reference to the root of the tree is the same as the space needed for a reference to a leaf.

In general you can assume each call to a method in Java takes the same amount of space on the stack. There is no way to allocate memory on the stack (or, not yet at least). In this method, no objects are created or destroyed on the heap, so the only space used is the space for the stack frames.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=394486&siteId=1