# -*- coding: utf - 8 - *-
class TreeNode(object):
def __init__(self, left=0, right=0, data=0):
self.left = left
self.right = right
self.data = data
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 create(self):
temp = input('enter a value:')
if temp is '#':
return 0
treenode = TreeNode(data=temp)
if self.root is 0:
self.root = treenode
treenode.left = self.create()
treenode.right = self.create()
使用create创建二叉树
代码如下:
#运行文件 在交互解释器下面运行
bt = BTree()
bt.create()
enter a value:9
enter a value:7
enter a value:6
enter a value:2
enter a value:1
enter a value:'#'
enter a value:'#'
enter a value:'#'
enter a value:5
enter a value:3
enter a value:'#'
enter a value:'#'
enter a value:4
enter a value:'#'
enter a value:'#'
enter a value:'#'
enter a value:8
enter a value:'#'
enter a value:'#'
通过 create 也可以得到同样的效果