简体   繁体   中英

Space complexity of printing all paths from root to leaf

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);
}

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 (ie 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) .

这将是O(n)最坏的情况,因为在这种情况下,您将查看树中的每个节点(n个节点)。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM