欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2016年05月24日 10:13:15   作者:家威  
二叉樹(shù)是最基本的數(shù)據(jù)結(jié)構(gòu),這里我們?cè)赑ython中使用類(lèi)的形式來(lái)實(shí)現(xiàn)二叉樹(shù)并且用內(nèi)置的方法來(lái)遍歷二叉樹(shù),下面就讓我們一起來(lái)看一下Python實(shí)現(xiàn)二叉樹(shù)結(jié)構(gòu)與進(jìn)行二叉樹(shù)遍歷的方法詳解

二叉樹(shù)的建立

2016524100535096.png (500×249)

使用類(lèi)的形式定義二叉樹(shù),可讀性更好

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)行二叉樹(shù)遍歷

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

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

#!/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())

相關(guān)文章

  • pytorch fine-tune 預(yù)訓(xùn)練的模型操作

    pytorch fine-tune 預(yù)訓(xùn)練的模型操作

    這篇文章主要介紹了pytorch fine-tune 預(yù)訓(xùn)練的模型操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • 為什么從Python 3.6開(kāi)始字典有序并效率更高

    為什么從Python 3.6開(kāi)始字典有序并效率更高

    這篇文章主要給大家介紹了關(guān)于為什么從Python 3.6開(kāi)始字典有序并效率更高的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • PyCharm創(chuàng)建Django項(xiàng)目的簡(jiǎn)單步驟記錄

    PyCharm創(chuàng)建Django項(xiàng)目的簡(jiǎn)單步驟記錄

    PyCharm是一種Python?IDE,帶有一整套可以幫助用戶在使用Python語(yǔ)言開(kāi)發(fā)時(shí)提高其效率的工具,下面這篇文章主要給大家介紹了關(guān)于利用PyCharm創(chuàng)建Django項(xiàng)目的簡(jiǎn)單步驟,需要的朋友可以參考下
    2022-07-07
  • 關(guān)于反爬蟲(chóng)的一些簡(jiǎn)單總結(jié)

    關(guān)于反爬蟲(chóng)的一些簡(jiǎn)單總結(jié)

    這篇文章主要介紹了關(guān)于反爬蟲(chóng)的一些簡(jiǎn)單總結(jié),具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • 手動(dòng)安裝python3.6的操作過(guò)程詳解

    手動(dòng)安裝python3.6的操作過(guò)程詳解

    這篇文章主要介紹了如何手動(dòng)安裝python3.6,本文給大家?guī)?lái)了安裝步驟,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-01-01
  • python多重繼承實(shí)例

    python多重繼承實(shí)例

    這篇文章主要介紹了python多重繼承實(shí)例,簡(jiǎn)單實(shí)用易于理解,需要的朋友可以參考下
    2014-10-10
  • 詳解python中的IO操作方法

    詳解python中的IO操作方法

    這篇文章主要介紹了Python實(shí)現(xiàn)IO操作的示例,是python入門(mén)必會(huì)得知識(shí)點(diǎn),將幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2022-01-01
  • 詳解如何使用Python網(wǎng)絡(luò)爬蟲(chóng)獲取招聘信息

    詳解如何使用Python網(wǎng)絡(luò)爬蟲(chóng)獲取招聘信息

    在疫情階段,想找一份不錯(cuò)的工作變得更為困難,很多人會(huì)選擇去網(wǎng)上看招聘信息??墒钦衅感畔⒂幸恍┦清e(cuò)綜復(fù)雜的。本文將為大家介紹用Python爬蟲(chóng)獲取招聘信息的方法,需要的可以參考一下
    2022-03-03
  • 解決ROC曲線畫(huà)出來(lái)只有一個(gè)點(diǎn)的問(wèn)題

    解決ROC曲線畫(huà)出來(lái)只有一個(gè)點(diǎn)的問(wèn)題

    今天小編就為大家分享一篇解決ROC曲線畫(huà)出來(lái)只有一個(gè)點(diǎn)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-02-02
  • Python如何實(shí)現(xiàn)遠(yuǎn)程方法調(diào)用

    Python如何實(shí)現(xiàn)遠(yuǎn)程方法調(diào)用

    這篇文章主要介紹了Python如何實(shí)現(xiàn)遠(yuǎn)程方法調(diào)用,文中講解非常細(xì)致,幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-08-08

最新評(píng)論