#coding:utf-8
class TreeNode(object):
def __init__(self, data, lchild=None, rchild=None):
self.lchild = lchild
self.rchild = rchild
self.data = data
class BTree:
def __init__(self):
self.root = None
def init(self, L=None):
'''
用L初始化树,如果L为空,手动输入初始化树
前序遍历,用#代表空节点
'''
def __init():
if L is None:
data = raw_input('in_put:')
else:
data = L.pop(0)
if data == '#':
return None
node = TreeNode(data)
node.lchild = __init()
node.rchild = __init()
return node
self.root = __init()
def pre_order(self, T=None):
def __pre_order(T):
if T:
print T.data,
__pre_order(T.lchild)
__pre_order(T.rchild)
__pre_order(self.root)
print
def in_order(self):
def __in_order(T):
if T:
__in_order(T.lchild)
print T.data,
__in_order(T.rchild)
__in_order(self.root)
print
def post_order(self):
def __post_order(T):
if T:
__post_order(T.lchild)
__post_order(T.rchild)
print T.data,
__post_order(self.root)
print
def breadth_first_search(self):
queue = [self.root]
while queue:
node = queue.pop(0)
if node:
print node.data,
if node.lchild:
queue.append(node.lchild)
if node.rchild:
queue.append(node.rchild)
print
def depth_first_search(self):
stack = [self.root]
while stack:
node = stack.pop()
print node.data,
if node.rchild:
stack.append(node.rchild)
if node.lchild:
stack.append(node.lchild)
print
def get_node_num(self):
def __get_node_num(T):
if T is None:
return 0
return 1 + __get_node_num(T.lchild) + __get_node_num(T.rchild)
return __get_node_num(self.root)
def get_leaf_num(self):
def __get_leaf_num(T):
if T:
if T.rchild is None and T.lchild is None:
return 1
else:
return __get_leaf_num(T.lchild) + __get_leaf_num(T.rchild)
else:
return 0
return __get_leaf_num(self.root)
def get_tree_hight(self):
def __get_tree_hight(T):
if T is None:
return 0
return 1 + max(__get_tree_hight(T.lchild), __get_tree_hight(T.rchild))
return __get_tree_hight(self.root)
def swap_left_right(self):
def __swap_left_right(T):
if T:
T.lchild, T.rchild = T.rchild, T.lchild
__swap_left_right(T.lchild)
__swap_left_right(T.rchild)
__swap_left_right(self.root)
def is_in_tree(self, data):
def __is_in_tree(T):
if T:
if T.data == data or T.data == data:
return True
else:
return __is_in_tree(T.lchild) or __is_in_tree(T.rchild)
else:
return False
return __is_in_tree(self.root)
@classmethod
def test(cls, L=None):
T = cls()
T.init(L)
print u'前序:'
T.pre_order()
print u'中序:'
T.in_order()
print u'后序:'
T.post_order()
print u'广度优先遍历:'
T.breadth_first_search()
print u'深度优先遍历:'
T.depth_first_search()
print u'树高:',T.get_tree_hight()
print u'叶节点数:',T.get_leaf_num()
print u'交换左右节点,广度遍历:'
T.swap_left_right()
T.breadth_first_search()
for i in xrange(10):
print u'%d 在树中:' % i, T.is_in_tree(i)
BTree.test([4,3,1,'#','#',5,1,'#','#','#',2,'#',3,'#','#'])
二叉树
最新推荐文章于 2021-11-23 09:47:01 发布