Python实现树的先序、中序、后序排序算法示例

时间:2021-11-13 08:52:56

本文实例讲述了Python实现树的先序、中序、后序排序算法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#encoding=utf-8
class Tree():
  def __init__(self,leftjd=0,rightjd=0,data=0):
    self.leftjd = leftjd
    self.rightjd = rightjd
    self.data = data
class Btree():
  def __init__(self,base=0):
    self.base = base
  #前序遍历 根左右
  def qout(self,jd):
    if jd == 0:
    return
  print jd.data
  self.qout(jd.leftjd)
  self.qout(jd.rightjd)
  #中序遍历 左根右
  def mout(self,jd):
  if jd == 0:
    return
  self.mout(jd.leftjd)
  print jd.data
  self.mout(jd.rightjd)
  #后序遍历 左右根
  def hout(self,jd):
  if jd == 0:
    return
  self.hout(jd.leftjd)
  self.hout(jd.rightjd)
  print jd.data
jd1 = Tree(data=8)
jd2 = Tree(data=9)
base = Tree(jd1,jd2,7)
x = Btree(base)
x.qout(x.base)
print '\r\n'
x.mout(x.base)
print '\r\n'
x.hout(x.base)

希望本文所述对大家Python程序设计有所帮助。