日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

数据结构之二叉树:折纸问题——11

發布時間:2024/7/5 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构之二叉树:折纸问题——11 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

數據結構之二叉樹:Python代碼解決折紙問題

折紙問題

  • 要求:請把一段紙條豎著放在桌子上,然后從紙條的下邊向上方對折1次,壓出折痕后展開。此時折痕是凹下去的,即折痕突起的方向指向紙條的背面。如果從紙條的下邊向上方連續對折2次,壓出折痕后展開,此時有三條折痕,從上到下依次是下折痕、下折痕和上折痕。


分析:
我們把對折后的紙張翻過來讓粉色朝下,這時把第-次對折產生的折痕看做是根結點,那第二次對折產生的下折痕就是該結點的左子結點,而第二次對折產生的上折痕就是該結點的右子結點,這樣我們就可以使用樹型數據結構來描述對折后產生的折痕。這棵樹有這樣的特點:

  • 根結點為下折痕;
  • 每一個結點的左子結點為下折痕;
  • 每一個結點的右子結點為 上折痕;
  • 畫成樹會是這樣:

    實現步驟:

    • 1.定義結點類
    • 2.構建深度為N的折痕樹;
    • 3.使用中序遍歷,打印出樹中所有結點的內容;

    構建深度為N的折痕樹:

    • 1.第一次對折,只有一條折痕,創建根結點;
    • 2.如果不是第一次對折,則使用隊列保存根結點;
    • 3.循環遍歷隊列:
      3.1從隊列中拿出一個結點;
      3.2如果這個結點的左子結點不為空,則把這個左子結點添加到隊列中;
      3.3如果這個結點的右子結點不為空,則把這個右子結點添加到隊列中;
      3.4判斷當前結點的左子結點和右子結點都不為空,如果是,則需要為當前結點創建一個值為down的左子結點 , 一個值為up的右子結點。

    方法介紹:

  • create_paper_folding_tree()創建折紙樹,queue為輔助隊列,初始時存入根結點(整棵樹),如果queue不為空,則將樹取出來,判斷其是否有左右子樹,如果有將左右子樹分別再放入queue,繼續循環判斷
  • print_this_tree()使用中序遍歷的方式打印結點的值
  • 接下來使用代碼實現,并將結點的值中序遍歷打印出來

    代碼實現

    class Node:def __init__(self, item):self.item = itemself.left = Noneself.right = Noneclass PaperFolding:def __init__(self):self.root = Nonedef create_paper_folding_tree(self, number):"""Emulate the process of paper-folding and create a binary tree"""for n in range(number):# When the first folding, assign 'down' to the root node.item and go on loopif n == 0:self.root = Node('down')continue# When not the first folding, level-orderly traverse from up to down,# and from left to right to create new leaves# Create a subsidiary list to traverse level-orderlyqueue = [self.root]while queue:# Pop from the left(prior to the left sub-tree)node = queue.pop(0)# Append nodes to queue(priority order: left->parent->right) and go on traversing in while loopif node.left:queue.append(node.left)if node.right:queue.append(node.right)if not node.left and not node.right: # Have come to the leaves# In paper-folding tree,# sub-tree on the left value will be 'down' and sub-tree on the right will be 'up'node.left = Node('down')node.right = Node('up')return self.rootdef print_this_tree(self):"""Traverse mid-orderly and print all values of the tree nodes"""if not self.root:returndef print_values(node):if node.left:print_values(node.left)print(node.item, end=' ') # Mid-order, left --> root --> rightif node.right:print_values(node.right)print_values(self.root)

    代碼測試

    if __name__ == '__main__':PF = PaperFolding()PF.create_paper_folding_tree(3)PF.print_this_tree()

    測試結果

    down down up down down up up

    對比折紙樹的層序遍歷,沒有問題

    總結

    以上是生活随笔為你收集整理的数据结构之二叉树:折纸问题——11的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。