劍指offer試題——重建二叉樹
阿新 • • 發佈:2018-04-12
部分 序列 des 完整 clas offer 根節點 整理 tin
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字。例如輸入前序遍歷序列{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 len(pre) == 0: return None if len(pre) == 1: return TreeNode(pre[0]) else: flag = TreeNode(pre[0]) flag.left= self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])]) flag.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tin[tin.index(pre[0])+1:] ) return flag
二叉樹理論基礎部分可以看大話數據結構第六章
有時間可以看完整理匯總一下,防止以後忘記
劍指offer試題——重建二叉樹