Traversal Complexities

Let's lay out our numeric conclusions for the traversal approaches:

preorder()2N+1{2N + 1}H+2{H + 2}
inorder()2N+1{2N + 1}H+2{H + 2}
postorder()2N+1{2N + 1}H+2{H + 2}

Where N{N} is the tree's order, and H{H} is the tree's height.

The number of calls and stack sizes are all the same. Now, recall the Proper Binary Tree Bounds Lemma: The height of a tree, denoted H,{H,} has the bounds:

O(logn)HO(n)O(\log n) ≤ H ≤ O(n)

where n{n} is the number of nodes. This yields the following complexities:

Traversal Method Time Complexity Space Complexity
preorder() O(n){O(n)} O(logn)HO(n){O(\log n) \leq H \leq O(n)}
inorder() O(n){O(n)} O(logn)HO(n){O(\log n) \leq H \leq O(n)}
postorder() O(n){O(n)} O(logn)HO(n){O(\log n) \leq H \leq O(n)}

Where n{n} is the tree's order, and H{H} is the tree's height.

Thus, traversing an entire binary tree has a time complexity of O(n).{O(n).} And the space complexity for such a traversal is at least O(logn),{O(\log n),} and at most O(n),{O(n),} depending on the tree's height.