数据结构之二叉树:折纸问题——11
生活随笔
收集整理的這篇文章主要介紹了
数据结构之二叉树:折纸问题——11
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
數據結構之二叉樹:Python代碼解決折紙問題
折紙問題
- 要求:請把一段紙條豎著放在桌子上,然后從紙條的下邊向上方對折1次,壓出折痕后展開。此時折痕是凹下去的,即折痕突起的方向指向紙條的背面。如果從紙條的下邊向上方連續對折2次,壓出折痕后展開,此時有三條折痕,從上到下依次是下折痕、下折痕和上折痕。
分析:
我們把對折后的紙張翻過來讓粉色朝下,這時把第-次對折產生的折痕看做是根結點,那第二次對折產生的下折痕就是該結點的左子結點,而第二次對折產生的上折痕就是該結點的右子結點,這樣我們就可以使用樹型數據結構來描述對折后產生的折痕。這棵樹有這樣的特點:
畫成樹會是這樣:
實現步驟:
- 1.定義結點類
- 2.構建深度為N的折痕樹;
- 3.使用中序遍歷,打印出樹中所有結點的內容;
構建深度為N的折痕樹:
- 1.第一次對折,只有一條折痕,創建根結點;
- 2.如果不是第一次對折,則使用隊列保存根結點;
- 3.循環遍歷隊列:
3.1從隊列中拿出一個結點;
3.2如果這個結點的左子結點不為空,則把這個左子結點添加到隊列中;
3.3如果這個結點的右子結點不為空,則把這個右子結點添加到隊列中;
3.4判斷當前結點的左子結點和右子結點都不為空,如果是,則需要為當前結點創建一個值為down的左子結點 , 一個值為up的右子結點。
方法介紹:
接下來使用代碼實現,并將結點的值中序遍歷打印出來
代碼實現
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Pytorch神经网络实战案例】11
- 下一篇: 报错:OMP: Error #15: I