一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術(shù)及教程分享平臺(tái)!
分類導(dǎo)航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務(wù)器之家 - 腳本之家 - Python - Python實(shí)現(xiàn)二叉樹結(jié)構(gòu)與進(jìn)行二叉樹遍歷的方法詳解

Python實(shí)現(xiàn)二叉樹結(jié)構(gòu)與進(jìn)行二叉樹遍歷的方法詳解

2020-08-23 13:56家威 Python

二叉樹是最基本的數(shù)據(jù)結(jié)構(gòu),這里我們?cè)赑ython中使用類的形式來實(shí)現(xiàn)二叉樹并且用內(nèi)置的方法來遍歷二叉樹,下面就讓我們一起來看一下Python實(shí)現(xiàn)二叉樹結(jié)構(gòu)與進(jìn)行二叉樹遍歷的方法詳解

二叉樹的建立

Python實(shí)現(xiàn)二叉樹結(jié)構(gòu)與進(jìn)行二叉樹遍歷的方法詳解

使用類的形式定義二叉樹,可讀性更好

?
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
class BinaryTree:
  def __init__(self, root):
    self.key = root
    self.left_child = None
    self.right_child = None
  def insert_left(self, new_node):
    if self.left_child == None:
      self.left_child = BinaryTree(new_node)
    else:
      t = BinaryTree(new_node)
      t.left_child = self.left_child
      self.left_child = t
  def insert_right(self, new_node):
    if self.right_child == None:
      self.right_child = BinaryTree(new_node)
    else:
      t = BinaryTree(new_node)
      t.right_child = self.right_child
      self.right_child = t
  def get_right_child(self):
    return self.right_child
  def get_left_child(self):
    return self.left_child
  def set_root_val(self, obj):
    self.key = obj
  def get_root_val(self):
    return self.key
 
r = BinaryTree('a')
print(r.get_root_val())
print(r.get_left_child())
r.insert_left('b')
print(r.get_left_child())
print(r.get_left_child().get_root_val())
r.insert_right('c')
print(r.get_right_child())
print(r.get_right_child().get_root_val())
r.get_right_child().set_root_val('hello')
print(r.get_right_child().get_root_val())

Python進(jìn)行二叉樹遍歷

需求:
python代碼實(shí)現(xiàn)二叉樹的:
1. 前序遍歷,打印出遍歷結(jié)果
2. 中序遍歷,打印出遍歷結(jié)果
3. 后序遍歷,打印出遍歷結(jié)果
4. 按樹的level遍歷,打印出遍歷結(jié)果
5. 結(jié)點(diǎn)的下一層如果沒有子節(jié)點(diǎn),以‘N'代替

方法:
使用defaultdict或者namedtuple表示二叉樹
使用StringIO方法,遍歷時(shí)寫入結(jié)果,最后打印出結(jié)果
打印結(jié)點(diǎn)值時(shí),如果為空,StringIO()寫入‘N '
采用遞歸訪問子節(jié)點(diǎn)
代碼

?
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
 
# test tree as below:
''' 1 / \ / \ / \ / \ 2 3 / \ / \ / \ / \ 4 5 6 N / \ / \ / \ 7 N N N 8 9 / \ / \ / \ N N N N N N '''
 
from collections import namedtuple
from io import StringIO
 
#define the node structure
Node = namedtuple('Node', ['data', 'left', 'right'])
#initialize the tree
tree = Node(1,
      Node(2,
         Node(4,
           Node(7, None, None),
           None),
         Node(5, None, None)),
      Node(3,
         Node(6,
           Node(8, None, None),
           Node(9, None, None)),
         None))
#read and write str in memory
output = StringIO()
 
 
#read the node and write the node's value
#if node is None, substitute with 'N '
def visitor(node):
  if node is not None:
    output.write('%i ' % node.data)
  else:
    output.write('N ')
 
 
#traversal the tree with different order
def traversal(node, order):
  if node is None:
    visitor(node)
  else:
    op = {
        'N': lambda: visitor(node),
        'L': lambda: traversal(node.left, order),
        'R': lambda: traversal(node.right, order),
    }
    for x in order:
      op[x]()
 
 
#traversal the tree level by level
def traversal_level_by_level(node):
  if node is not None:
    current_level = [node]
    while current_level:
      next_level = list()
      for n in current_level:
        if type(n) is str:
          output.write('N ')
        else:
          output.write('%i ' % n.data)
          if n.left is not None:
            next_level.append(n.left)
          else:
            next_level.append('N')
          if n.right is not None:
            next_level.append(n.right)
          else:
            next_level.append('N ')
 
      output.write('\n')
      current_level = next_level
 
 
if __name__ == '__main__':
  for order in ['NLR', 'LNR', 'LRN']:
    if order == 'NLR':
      output.write('this is preorder traversal:')
      traversal(tree, order)
      output.write('\n')
    elif order == 'LNR':
      output.write('this is inorder traversal:')
      traversal(tree, order)
      output.write('\n')
    else:
      output.write('this is postorder traversal:')
      traversal(tree, order)
      output.write('\n')
 
  output.write('traversal level by level as below:'+'\n')
  traversal_level_by_level(tree)
 
  print(output.getvalue())

 

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 色五夜婷婷 | 精品无人区乱码1区2区3区免费 | 国产免费看视频 | 国产18在线 | 欧美一区二区三区久久久 | 精品久久久久久国产 | 国内自拍2020 | 亚洲欧美影院 | 亚洲情欲网 | 亚洲伦理视频 | 亚洲精品综合网 | 欧美日韩亚洲综合久久久 | 手机在线伦理片 | 亚欧有色在线观看免费版高清 | 美女污视频 | bt伙计最新合集 | 欧美穿高跟鞋做爰 | 国产在线一区二区杨幂 | 日处女b| 国产大片视频免费观看 | chinese456老年gay| 拔插拔插8x8x海外华人免费视频 | 暖暖的免费观看高清视频韩国 | 四虎精品影视 | 无人区尖叫之夜美女姐姐视频 | 娇妻被健身教练挺进小说阅读 | jj视频免费看 | 99热久久这里只有精品23 | 四虎影院永久在线 | 四虎伊人 | 99精品全国免费7观看视频 | 精品久久一 | 国产chinese男男gaygay | 青春草视频免费观看 | 精品国偷自产在线 | 无人视频在线观看完整版高清 | 地址二地址三2021变更 | 国产成人在线视频播放 | 日本一区二区三区国产 | 深夜精品高中女学生 | 为什么丈夫插我我却喜欢被打着插 |