1. 程式人生 > >[python版]劍指offer -- 重建二叉樹

[python版]劍指offer -- 重建二叉樹

題目描述

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{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:return None
        ret = TreeNode(pre[0])
        index = tin.index(pre[0])
        ret.left = self.reConstructBinaryTree(pre[1:index+1], tin[:index])
        ret.right = self.reConstructBinaryTree(pre[index+1:], tin[index+1:])
        return ret

另有牛客網精簡實現方法:
思路:採用list的pop方法,在建立左子樹時將左子樹的結點從pre中一個個的pop出去了,這樣在構建右子樹時,前序列表pre中已經不再包含左子樹的結點。

class Solution:
    def reConstructBinaryTree(self, pre, tin):
        if not pre or not tin:
            return None
        root = TreeNode(pre.pop(0))
        index = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre, tin[:index])
        root.right = self.reConstructBinaryTree(pre, tin[index + 1:])
        return root