国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python數據結構與算法之二叉樹結構定義與遍歷方法詳解

2020-02-16 11:04:07
字體:
來源:轉載
供稿:網友

本文實例講述了Python數據結構與算法之二叉樹結構定義與遍歷方法。分享給大家供大家參考,具體如下:

先序遍歷,中序遍歷,后序遍歷 ,區別在于三條核心語句的位置

層序遍歷  采用隊列的遍歷操作第一次訪問根,在訪問根的左孩子,接著訪問根的有孩子,然后下一層 自左向右一一訪問同層的結點

# 先序遍歷# 訪問結點,遍歷左子樹,如果左子樹為空,則遍歷右子樹,# 如果右子樹為空,則向上走到一個可以向右走的結點,繼續該過程preorder(t):  if t:    print t.value    preorder t.L    preorder t.R# 中序遍歷# 從根開始,一直走向左下方,直到無結點可以走則停下,訪問該節點# 然后走向右下方到結點,繼續走向左下方:如果結點無右孩子,則向上走回父親結點inorder(t):  inorder(t.L)  print t.value  inorder(t.R)# 后序遍歷inorder(t):  inorder(t.L)  inorder(t.R)  print t.value# 二叉樹結點類型class BTNode:  def __init__(self,value,lft=None,rgt=None):    self.value = value    self.lft = lft     # 結點左分支 BTNode    self.rgt = rgt     # 結點右分支 BTNode

為了方便起見,定義一些打印操作

class BinTree():  def __init__(self):    self.root = None  # 創建一個空的二叉樹  def isEmpty(self):   # 判斷二叉樹是否為空    if self.root is None: return True    else: return False  def makeBT(self,bt,L=None,R=None):    # 從當前結點創建二叉樹    bt.lft = L    bt.rgt = R  def returnBTdict(self):       # 返回二叉樹的字典模式    if self.isEmpty():       return None    def rec(bt=None,R=True):      if R==True:        bt = self.root        return {'root':{'value':bt.value,"L":rec(bt.lft,False),                        "R":rec(bt.rgt,False)} }      else:        if bt==None:          return None        else:          return {"value":bt.value,              "L":rec(bt.lft,False) if bt.lft != None else None,              "R":rec(bt.rgt,False) if bt.rgt != None else None}      return None    return rec()  def __repr__(self):       # 將二叉樹結構打印為字典結構    return str(self.returnBTdict())

下面是各種遍歷方法,添加到樹的類中

def printT_VLR(self,bt=None,rec_count = 0):   # 輸出二叉樹結構(先序遍歷)    # rec_count 用于計算遞歸深度 以便輸出最后的換行符    """    # 先序遍歷    # 訪問結點,遍歷左子樹,如果左子樹為空,則遍歷右子樹,    # 如果右子樹為空,則向上走到一個可以向右走的結點,繼續該過程    preorder(t):      if t:        print t.value        preorder t.L        preorder t.R    """    if bt==None:       bt = self.root      print bt.value,    btL, btR = bt.lft, bt.rgt    if btL != None:      print btL.value,;  rec_count += 1;   self.printT_VLR(btL,rec_count);   rec_count -= 1    if btR != None:      print btR.value,;  rec_count += 1;   self.printT_VLR(btR,rec_count);   rec_count -= 1    if rec_count == 0:      print "/n"def printT_LVR(self,bt=None):    """    # 中序遍歷    # 從根開始,一直走向左下方,直到無結點可以走則停下,訪問該節點    # 然后走向右下方到結點,繼續走向左下方:如果結點無右孩子,則向上走回父親結點    inorder(t):      inorder(t.L)      print t.value      inorder(t.R)    """    if bt==None:      bt = self.root    btL, btR = bt.lft, bt.rgt    if btL != None:      self.printT_LVR(btL)    print bt.value,    if btR != None:      self.printT_LVR(btR)def printT_LRV(self,bt=None):    """    # 后序遍歷    inorder(t):      inorder(t.L)      inorder(t.R)      print t.value    """    if bt==None:      bt = self.root    btL, btR = bt.lft, bt.rgt    if btL != None:      self.printT_LRV(btL)    if btR != None:      self.printT_LRV(btR)    print bt.value,def printT_levelorder(self):    """    層序遍歷 采用隊列的遍歷操作    第一次訪問根,在訪問根的左孩子,接著訪問根的有孩子,然后下一層    自左向右一一訪問同層的結點    """    btdict = self.returnBTdict()    q = []    q.append(btdict['root'])    while q:      tn = q.pop(0)  # 從隊列中彈出一個結點(也是一個字典)      print tn["value"],      if tn["L"]!=None:        q.append(tn["L"])      if tn["R"]!=None:        q.append(tn["R"])            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 灵丘县| 稷山县| 长兴县| 侯马市| 高陵县| 湘阴县| 文昌市| 通州区| 平南县| 内黄县| 邢台县| 仪征市| 田阳县| 祁东县| 拉孜县| 罗城| 文安县| 运城市| 军事| 合作市| 罗江县| 潮安县| 象山县| 乌兰县| 宁河县| 格尔木市| 饶平县| 昌吉市| 大石桥市| 南昌市| 略阳县| 正蓝旗| 岢岚县| 班玛县| 连南| 怀化市| 东辽县| 东莞市| 武定县| 扶风县| 吉木萨尔县|