python數(shù)據(jù)結(jié)構(gòu)之二叉樹的建立實例
先建立二叉樹節(jié)點,有一個data數(shù)據(jù)域,left,right 兩個指針域
# -*- coding: utf - 8 - *-
class TreeNode(object):
def __init__(self, left=0, right=0, data=0):
self.left = left
self.right = right
self.data = data
class BTree(object):
def __init__(self, root=0):
self.root = root
手動建立二叉樹
node1 = TreeNode(data=1)
node2 = TreeNode(node1, 0, 2)
node3 = TreeNode(data=3)
node4 = TreeNode(data=4)
node5 = TreeNode(node3, node4, 5)
node6 = TreeNode(node2, node5, 6)
node7 = TreeNode(node6, 0, 7)
node8 = TreeNode(data=8)
root = TreeNode(node7, node8, 'root')
bt = BTree(root)
然后會生成下面的二叉樹
# 生成的二叉樹
# ------------------------
# root
# 7 8
# 6
# 2 5
# 1 3 4
#
# -------------------------
除了 手動一個個的制定 node 節(jié)點,還可以創(chuàng)建一個 create 方法,接受用戶輸入添加二叉樹節(jié)點。。。使用前續(xù)方式添加 ,代碼如下:
# -*- coding: utf - 8 - *-
class TreeNode(object):
def __init__(self, left=0, right=0, data=0):
self.left = left
self.right = right
self.data = data
class BTree(object):
def __init__(self, root=0):
self.root = root
def is_empty(self):
if self.root is 0:
return True
else:
return False
def create(self):
temp = input('enter a value:')
if temp is '#':
return 0
treenode = TreeNode(data=temp)
if self.root is 0:
self.root = treenode
treenode.left = self.create()
treenode.right = self.create()
使用create創(chuàng)建二叉樹
#運行文件 在交互解釋器下面運行
bt = BTree()
bt.create()
enter a value:9
enter a value:7
enter a value:6
enter a value:2
enter a value:1
enter a value:'#'
enter a value:'#'
enter a value:'#'
enter a value:5
enter a value:3
enter a value:'#'
enter a value:'#'
enter a value:4
enter a value:'#'
enter a value:'#'
enter a value:'#'
enter a value:8
enter a value:'#'
enter a value:'#'
通過 create 也可以得到同樣的效果
相關(guān)文章
python光學(xué)仿真學(xué)習(xí)wxpython創(chuàng)建手速測試程序
這篇文章主要介紹了python光學(xué)仿真學(xué)習(xí)使用wxpython創(chuàng)建一個手速測試程序示例的實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10解決jupyter notebook圖片顯示模糊和保存清晰圖片的操作
這篇文章主要介紹了解決jupyter notebook圖片顯示模糊和保存清晰圖片的操作方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04Python利用Pillow(PIL)庫實現(xiàn)驗證碼圖片的全過程
這篇文章主要給大家介紹了關(guān)于Python利用Pillow(PIL)庫實現(xiàn)驗證碼圖片的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10python使用xauth方式登錄飯否網(wǎng)然后發(fā)消息
這篇文章主要介紹了python使用xauth方式登錄飯否網(wǎng)然后發(fā)消息示例,需要的朋友可以參考下2014-04-04Python使用Tkinter實現(xiàn)滾動抽獎器效果
Tkinter 是 Python 的標(biāo)準(zhǔn) GUI(Graphical User Interface,圖形用戶接口)庫,Python 使用 Tkinter 可以快速地創(chuàng)建 GUI 應(yīng)用程序。這篇文章主要介紹了Python使用Tkinter實現(xiàn)滾動抽獎器,需要的朋友可以參考下2020-01-01Tensorflow實現(xiàn)酸奶銷量預(yù)測分析
這篇文章主要為大家詳細(xì)介紹了Tensorflow酸奶銷量預(yù)測分析,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07