激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

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

服務器之家 - 腳本之家 - Python - Python實現二叉樹結構與進行二叉樹遍歷的方法詳解

Python實現二叉樹結構與進行二叉樹遍歷的方法詳解

2020-08-23 13:56家威 Python

二叉樹是最基本的數據結構,這里我們在Python中使用類的形式來實現二叉樹并且用內置的方法來遍歷二叉樹,下面就讓我們一起來看一下Python實現二叉樹結構與進行二叉樹遍歷的方法詳解

二叉樹的建立

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
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進行二叉樹遍歷

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

方法:
使用defaultdict或者namedtuple表示二叉樹
使用StringIO方法,遍歷時寫入結果,最后打印出結果
打印結點值時,如果為空,StringIO()寫入‘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())

 

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产免费观看视频 | 日本a v免费观看 | 国产精品免费看 | 中文区永久区 | 99久久精约久久久久久清纯 | 泰剧19禁啪啪无遮挡大尺度 | 午夜偷拍视频 | 免费观看视频91 | 黄色毛片18| 日日做夜夜操 | 精品小视频 | av噜噜在线 | 欧美大电影免费观看 | 午夜男人免费视频 | 久久综合一区二区 | 国产羞羞视频在线观看免费应用 | 又黄又爽又色无遮挡免费 | 免费一级a毛片在线播放视 日日草夜夜操 | 性生活视频软件 | 一区二区三区国产视频 | 高清一区二区在线观看 | 毛片在线免费播放 | 亚洲福利在线视频 | 九九综合视频 | 香蕉视频99 | 免费观看国产精品视频 | 日韩欧美高清一区 | 国产91九色在线播放 | 日日噜噜夜夜爽 | 法国极品成人h版 | 中国杭州少妇xxxx做受 | 黑人一级片视频 | 亚洲精品一区二区三区免 | 国产精品免费久久久 | 欧美日韩手机在线观看 | 国产成人羞羞视频在线 | 国产日韩中文字幕 | videos真实高潮xxxx | 99亚洲视频 | 亚洲乱搞| 一级在线免费观看视频 |