二叉树的实现为非递归实现,遍历方法就写了一个,traversal(self, root), 其实先序遍历、中序遍历和后序遍历的区别就一个,代码注释里有,就是 print root.data, 这句代码的位置的区别,非常简单。
完整代码:
#!/usr/bin/python
# Filename: BTree.py
class BTNode:
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
class BTree:
def __init__(self):
self.root = None
def insert(self, data):
r = self.root
if r == None:
self.root = BTNode(data, None, None)
return
while True:
if r.data > data:
if r.left == None:
r.left = BTNode(data, None, None)
break
else:
r = r.left
else:
if r.right == None:
r.right = BTNode(data, None, None)
break
else:
r = r.