I was wondering if it\'s possible to print a binary tree in breadth first order while using only O(1) space?
The difficult part is that one have to use additional sp
An interesting special case is heaps.
From heapq docs:
Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for which
heap[k] <= heap[2*k+1]andheap[k] <= heap[2*k+2]for all k, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that its smallest element is always the root,heap[0]. [explanation by François Pinard]
How a tree represented in memory (indexes of the array):
0
1 2
3 4 5 6
7 8 9 10 11 12 13 14
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
In this case nodes in the array are already stored in a breadth first order.
for value in the_heap:
print(value)
O(1) in space.