#用类定义二叉树
class BTree:
def
__init__(self,value):
#左儿子
self.left =
None
#节点值
self.data =
value
#右儿子
self.right
= None
#向左子树插入节点
def
insertLeft(self,value):
self.left =
BTree(value)
return
self.left
#向右子树插入节点
def insertRight(self,value):
self.right
= BTree(value)
return
self.right
#输出节点数据
def show(self):
self.data
#判断是否为叶子
def isLeaf(self):
return ((not self.left) and
(not self.right))
#得到右孩子
def getRightChild(self):
return self.right
#得到左孩子
def getLeftChild(self):
return self.left
#先序遍历
def preorder(self,node):
if node.data:
node.show()
if
node.left:
self.preorder(node.left)
if
node.right:
self.preorder(node.right)
#中序遍历
def inorder(self,node):
if node.data:
if
node.left:
self.inorder(node.left)
node.show()
if
node.right:
self.inorder(node.right)
#后序遍历
def postorder(self,node):
if node.data:
if
node.left:
self.postorder(node.left)
if
node.right:
self.postorder(node.right)
node.show()
#树高
def height(tree):
if tree ==
None:
return -1
else:
return 1 +
max(height(tree.left),height(tree.right))
if __name__ == '__main__':
Root = BTree('D')
B = Root.insertLeft('B')
E = Root.insertRight('E')
A = B.insertLeft('A')
C = B.insertRight('C')
G = E.insertRight('G')
F = G.insertLeft('F')
'***********************'
print 'Binary tree
pre-travels'
'***********************'
Root.preorder(Root)
'***********************'
print 'Binary tree
in-travels'
'***********************'
Root.inorder(Root)
'***********************'
print 'Binary tree
post-travels'
'***********************'
Root.postorder(Root)
print A.isLeaf()
B.getLeftChild().show()
B.getRightChild().show()
print height(Root)