Why is the spatial complexity of a recursive workaround O (h) rather than O (n)

Thus, I know that the spatial complexity of a recursive path traversal is O (h), not O (n) like h = tree height and n = number of nodes in the tree.

Why? Let's say this is the code to work around:

public void inorderPrint (TreeNode root) {

    if (root == null) {
        return;
    }

    inorderPrint(root.left);
    System.out.println(root.data);
    inorderPrint(root.right);

}

We push n memory addresses onto the call stack, so the complexity of the space should be O (n).

What am I missing?

+4
source share
2 answers

Addresses are removed from the stack upon return. This space is reused when creating a new call from a level closer to the root. Thus, the maximum number of memory addresses on the stack is simultaneously the height of the tree.

+4

IMHO, O(n). Big O, , n.

, , O(n) . :

  1
 / \
    2
   / \
      3

, n = 3

, = 3

  1
 / \
    2
   / \
      3
     / \
        4
       / \

, n = 4

, = 4

, , O(n) - w.r.t. . / n. . , , .

, O(h) <= O(n). , O(n), . , O(h) - , @StefanHaustein .

0

Source: https://habr.com/ru/post/1664063/


All Articles