首页 技术 正文
技术 2022年11月21日
0 收藏 318 点赞 3,010 浏览 1384 个字

Python实现二叉树的左中右序遍历

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/3/18 12:31
# @Author : baoshan
# @Site :
# @File : binarytree.py
# @Software: PyCharm Community Edition# python 实现二叉树的左中右序遍历class Node(object):
def __init__(self, index):
self.index = index
self.left_child = None
self.right_child = Noneclass BinaryTree(Node):
def __init__(self, root):
self.root = root def pre_travel(self, node):
if not node:
return
print(node.index)
self.pre_travel(node.left_child)
self.pre_travel(node.right_child) def mid_travel(self, node):
if not node:
return
self.mid_travel(node.left_child)
print(node.index)
self.mid_travel(node.right_child) def suf_travel(self, node):
if not node:
return
self.suf_travel(node.left_child)
self.suf_travel(node.right_child)
print(node.index)node_dict = {}
for i in range(1, 10):
node_dict[i] = Node(i)node_dict[1].left_child = node_dict[2]
node_dict[1].right_child = node_dict[3]
node_dict[2].left_child = node_dict[5]
node_dict[2].right_child = node_dict[6]
node_dict[3].left_child = node_dict[7]
node_dict[7].left_child = node_dict[8]
node_dict[7].right_child = node_dict[9]tree = BinaryTree(node_dict[1])
print('---左序遍历---')
tree.pre_travel(tree.root)
print('---中序遍历---')
tree.mid_travel(tree.root)
print('---右序遍历---')
tree.suf_travel(tree.root)

输出结果:

/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/baoshan/PycharmProjects/myProject/python_weixin_study/binarytree.py
---左序遍历---
1
2
5
6
3
7
8
9
---中序遍历---
5
2
6
1
8
7
9
3
---右序遍历---
5
6
2
8
9
7
3
1Process finished with exit code 0

请各位大虾指教!

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,999
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,357
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,140
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848