刷題平臺:牛客網php
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。ui
一般樹有以下幾種遍歷方式:url
本題爲前序遍歷和中序遍歷,最少須要兩種遍歷方式,才能重建二叉樹。spa
前序遍歷序列中,第一個數字老是樹的根結點的值。在中序遍歷序列中,根結點的值在序列的中間,左子樹的結點的值位於根結點的值的左邊,而右子樹的結點的值位於根結點的值的右邊。剩下的咱們能夠遞歸來實現,具體如圖:code
Python:blog
# -*- 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 len(pre) == 0: return None elif len(pre) == 1: return TreeNode(pre[0]) else: root = TreeNode(pre[0]) pos = tin.index(pre[0]) root.left = self.reConstructBinaryTree(pre[1:pos+1], tin[:pos]) root.right = self.reConstructBinaryTree(pre[pos+1:], tin[pos+1:]) return root