I have implement tree preorder traversal in python, but found that my recursive version is faster than iteration version.
code is as below:
from __future__ import print_function
import time
class Tree():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def build_tree(string):
nodes = [0] + [Tree(s) for s in string]
for i in range(2, len(nodes)):
p = i/2
if i%2 == 0:
nodes[p].left = nodes[i]
else:
nodes[p].right = nodes[i]
return nodes[1]
def preorder(tree):
if tree:
# print(tree.value,end='')
preorder(tree.left)
preorder(tree.right)
def preorder2(tree):
t = tree
s = []
while t or s:
while t:
# print(t.value,end='')
s.append(t)
t = t.left
if s:
t = s.pop()
t = t.right
def main():
tree = build_tree('abcdefghi'*1000)
t = time.time()
for _ in range(100):
preorder(tree)
print(time.time() - t)
t = time.time()
for _ in range(100):
preorder2(tree)
print(time.time() - t)
if __name__ == '__main__':
main()
results:
0.751042842865
1.0220580101
It means recursive version is about 25% faster. I search a lot, everybody says recursive should be slower, I just wonder why it is not the case in my code?
poporappend? The output of both traversals are same, so it is not the order of traversal that's causing the difference in performance.