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

劍指offer - 重建二叉樹

題目描述

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


每顆子樹的根節點肯定是pre子陣列的首元素,所以每次新建一個子樹的根節點。每次將左右兩顆子樹當成新的子樹進行處理,中序的左右子樹索引很好找,前序的開始結束索引通過計算中序中左右子樹的大小來計算,然後遞迴求解

# -*- 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
        root = TreeNode(pre.pop(0))
        position = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre, tin[:position])
        root.right = self.reConstructBinaryTree(pre, tin[position + 1:])
        return root

執行時間:53ms

佔用記憶體:5728k