# 二叉树的遍历(Python)

class Node():
def __init__(self, item):
self.value = item
self.lchild = None
self.rchild = None

class Tree():
def __init__(self):
self.root = None
pass
def PreOrderTraverse(self, root)    #前序遍历
pass
def InOrderTraverse(self, root)     #中序遍历
pass
def PostOrderTraverse(self, root)   #后序遍历
pass

def Addnode(self, item):
node = Node(item)

if self.root == None:
self.root = node

else:
q = [self.root]

while True:
pop_node = q.pop(0)
if pop_node.lchild==None:
pop_node.lchild = node
return
elif pop_node.rchild==None:
pop_node.rchild = node
return
else:
q.append(pop_node.lchild)
q.append(pop_node.rchild)

def PreOrderTraverse(self, root):
'''preorder traverse
前序遍历
'''
if root is None:
return []
result = [root.value]
left_item = self.PreOrderTraverse(root.lchild)
right_item = self.PreOrderTraverse(root.rchild)
return result + left_item + right_item

def InOrderTraverse(self, root):
'''inorder traverse
中序遍历
'''
if root is None:
return []
result = [root.value]
left_item = self.InOrderTraverse(root.lchild)
right_item = self.InOrderTraverse(root.rchild)
return left_item + result +  right_item

def PostOrderTraverse(self, root):
'''postorder traverse
后序遍历
'''
if root is None:
return []
result = [root.value]
left_item = self.PostOrderTraverse(root.lchild)
right_item = self.PostOrderTraverse(root.rchild)
return left_item  +  right_item + result

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120