劍指offer31 --- 重建二叉樹

劍指offer31 — 重建二叉樹

題目

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序描述遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

分析

手動重建流程圖:
在這裏插入圖片描述

算法步驟圖:
在這裏插入圖片描述

代碼

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回構造的TreeNode根節點
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if not pre or not tin or len(pre)!= len(tin):
            return None
        
        # 1.找到root以及其在中序中的位置
        root = pre[0]
        rootNode = TreeNode(root)
        pos = tin.index(root)
        
        # 2.新建列表,存儲root的左右子樹的前序和中序
        tinLeft = tin[:pos]
        tinRight = tin[pos+1:]
        preLeft = pre[1:pos+1]
        preRight = pre[pos+1:]
        
        # 3. 遞歸;左右子樹分別作爲一個新樹開始找其根結點以及左右子樹
        leftNode = self.reConstructBinaryTree(preLeft, tinLeft)
        rightNode = self.reConstructBinaryTree(preRight, tinRight)
        
        # 判斷leftNode和rightNode是否爲空,若不爲空,則建立其和root的關係
        if leftNode:
            rootNode.left = leftNode
        if rightNode:
            rootNode.right = rightNode
        return rootNode

牛客網該題鏈接

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