python构造二叉树_python实现二叉树的构建和遍历

#coding=utf-8

classNode(object):def __init__(self, data=None, left_child=None, right_child=None):

self.data=data

self.left_child=left_child

self.right_child=right_childclassBTree(object):def __init__(self):

self.root=Nonedefadd_node(self, data):

node=Node(data)if self.root isNone:

self.root=nodereturntmp_queue=[self.root]whileTrue:

current_node=tmp_queue.pop(0)if current_node isNone:return

if current_node.left_child isNone:

current_node.left_child=nodereturn

elif current_node.right_child isNone:

current_node.right_child=nodereturntmp_queue.append(current_node.left_child)

tmp_queue.append(current_node.right_child)deffront_travel(self, node):"""先序遍历"""

if node isNone:return

print(node.data)

self.front_travel(node.left_child)

self.front_travel(node.right_child)defmiddle_travel(self, node):"""中序遍历"""

if node isNone:returnself.middle_travel(node.left_child)print(node.data)

self.middle_travel(node.right_child)deflast_travel(self, node):"""后序遍历"""

if node isNone:returnself.last_travel(node.left_child)

self.last_travel(node.right_child)print(node.data)deflevel_travel(self):"""层次遍历"""tmp_queue=[self.root]whileTrue:if len(tmp_queue) ==0:print("travel finish")returncurrent_node=tmp_queue.pop(0)print(current_node.data)ifcurrent_node.left_child:

tmp_queue.append(current_node.left_child)ifcurrent_node.right_child:

tmp_queue.append(current_node.right_child)deffront(self):"""堆栈前序遍历"""

if notself.root:returntmp_stack=[]

node=self.rootwhile tmp_stack ornode:whilenode:print(node.data)

tmp_stack.append(node)

node=node.left_child

node=tmp_stack.pop()

node=node.right_childdefmiddle(self):"""堆栈中序遍历"""

if notself.root:returntmp_stack=[]

node=self.rootwhile tmp_stack ornode:whilenode:

tmp_stack.append(node)

node=node.left_child

node=tmp_stack.pop()print(node.data)

node=node.right_childdeflast(self):"""堆栈后序遍历,较难"""

if notself.root:returntmp_node=self.root

tmp_stack=[]while tmp_node ortmp_stack:whiletmp_node:

tmp_stack.append(tmp_node)

tmp_node= tmp_node.left_child ortmp_node.right_child

tmp_node=tmp_stack.pop()print(tmp_node.data)if tmp_stack and tmp_stack[-1].left_child istmp_node:

tmp_node= tmp_stack[-1].right_childelse:

tmp_node=Noneif __name__ == "__main__":

tree=BTree()for i in range(1, 20):

tree.add_node(i)#tree.level_travel() # 广度遍历

#tree.front_travel(tree.root) # 递归前序遍历

#tree.middle_travel(tree.root) # 递归中序遍历

tree.last_travel(tree.root) #递归后序遍历

print("---" * 20)#tree.front() # 堆栈前序遍历

#tree.middle() # 堆栈中序遍历

tree.last() #堆栈后序遍历

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值