python二叉树遍历的实现方法
#!/usr/bin/python
# -*- coding: utf-8 -*-
class treenode(object):
def __init__(self,data=0,left=0,right=0):
self.data = data
self.left = left
self.right = right
class btree(object):
def __init__(self,root=0):
self.root = root
def is_empty(self):
if self.root is 0:
return true
else:
return false
def preorder(self,treenode):
if treenode is 0:
return
print treenode.data
self.preorder(treenode.left)
self.preorder(treenode.right)
def inorder(self,treenode):
if treenode is 0:
return
self.inorder(treenode.left)
print treenode.data
self.inorder(treenode.right)
def postorder(self,treenode):
if treenode is 0:
return
self.postorder(treenode.left)
self.postorder(treenode.right)
print treenode.data
n1 = treenode(data=1)
n2 = treenode(2,n1,0)
n3 = treenode(3)
n4 = treenode(4)
n5 = treenode(5,n3,n4)
n6 = treenode(6,n2,n5)
n7 = treenode(7,n6,0)
n8 = treenode(8)
root = treenode('root',n7,n8)
bt = btree(root)
print 'preorder......'
print bt.preorder(bt.root)
print 'inorder......'
print bt.inorder(bt.root)
print 'postorder.....'
print bt.postorder(bt.root)
结果:
preorder......
root
7
6
2
1
5
3
4
8
inorder......
1
2
6
3
5
4
7
root
8
postorder.....
1
2
3
4
5
6
7
8
root
上一篇: Python查找相似单词的方法