1
votes

What is the space complexity of storing a path ie. nodes of a binary tree from root to a particular leaf in an array?

Basically, I am looking for space complexity of the following algorithm:

public void printPath () {
    doPrint(root, new ArrayList<TreeNode>());
}


private void doPrint(TreeNode node, List<TreeNode> path) {
    if (node == null) return;

    path.add(node);

    if (node.left == null && node.right == null) {
        System.out.println("Path from root: " + root.item + " to leaf: " + node.item + " - ");
        for (TreeNode treeNode : path) {
            System.out.print(treeNode.item + " ");
        }
        System.out.println();
    }

    doPrint(node.left , path);
    doPrint(node.right, path);

    path.remove(path.size() - 1);
}
3

3 Answers

2
votes

If your tree is balanced then it will be O(log n). This is because a balanced binary tree has twice as many nodes on each subsequent level, so if you double the quantity of nodes in the tree it only adds a single additional layer.

The path only holds the nodes that are parents of the current node, so it is not the case that you will end up holding the entire tree.

If your tree is completely unbalanced (i.e. every node has only a single child or less) then you will end up holding the entire tree in the list, as you must traverse every node in the tree to reach the single leaf. In this case it will be O(n).

1
votes

It would be O(n) worst case, because in that case you would look at every node (n nodes) in the tree.

1
votes

You are storing the all the nodes that lie on the path from the root to a particular leaf in the List.

If the binary tree is height balanced or it is a full/complete binary tree, the worst case time and space complexity is O(log n), where n is the number of nodes in the binary tree.

If we do not have any prior information of the type of binary tree, then the worst case time and space complexity is O(n) since the tree can be of the form that there is only the left child present or only the right child present.