已知後序和中序求先序 python

根據後序和中序求先序:

按照常規思路遞歸實現,先遞歸生成左子樹,再遞歸生成右子樹

class node:                          #定義節點結構
    def __init__(self, value = None, left = None, right=None):
        self.value = value
        self.left = left
        self.right = right

def GetTwoTree(str1, str2):          #str1爲後序  str2爲中序
    root = node(str1[-1])            #先給第一個值
    Index = str2.index(root.value)   #根在中序中的索引

    leftstr2 = str2[: Index]         #中序中的左半部分
    maxindex = -1
    for i in leftstr2:               # 分離後序序列
        tmpindex = str1.index(i)
        if maxindex < tmpindex:
            maxindex = tmpindex
    if len(leftstr2) == 1:           #如果只有一個元素
        root.left = node(leftstr2)   #直接賦值
    elif len(leftstr2) == 0:         #如果沒有元素 
        root.left = None             #空
    else:                            #否則遞歸
        root.left = GetTwoTree(str1[:maxindex+1], leftstr2)   #遞歸構造左子樹

    rightstr2 = str2[Index+1:]          #中序中的右半部分
    if len(rightstr2) == 1:
        root.right = node(rightstr2)
    elif len(rightstr2) == 0:
        root.right = None
    else:
        root.right = GetTwoTree(str1[maxindex+1:-1], rightstr2)   #遞歸構造右子樹
    return root

def preTraverse(root):  #遞歸先序遍歷
    if root != None:
        print(root.value)
        preTraverse(root.left)
        preTraverse(root.right)

if __name__ == '__main__':
    str1 = 'FCDBGEA'                     #str1爲後序結果  str2爲中序結果
    str2 = 'CFBDAEG'
    root = GetTwoTree(str1, str2)        #構造二叉樹
    preTraverse(root)                    #遍歷輸出

補充:

根據完全二叉樹的層次遍歷序列順序構造二叉樹
class node:
    def __init__(self, value = None, left = None, right = None):
        self.value = value
        self.left = left
        self.right = right

Quepre = [0,1,2,3,4,5,6]

Que = [0]               #保證原序列從1開始編號
for i in Quepre:
    Que.append(node(i))
for i in range(1, len(Que)//2):
    Que[i].left = Que[i*2]
    Que[i].right = Que[i*2+1]

def preTraverse(root):  # 遞歸先序遍歷
    if root != None:
        print(root.value)
        preTraverse(root.left)
        preTraverse(root.right)

preTraverse(Que[1])

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章