【剑指Offer】16重建二叉树
生活随笔
收集整理的這篇文章主要介紹了
【剑指Offer】16重建二叉树
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結(jié)果,請重建出該二叉樹。假設(shè)輸入的前序遍歷和中序遍歷的結(jié)果中都不含重復的數(shù)字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹并返回。
時間限制:1秒;空間限制:32768K
解題思路
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution:# 返回構(gòu)造的TreeNode根節(jié)點def reConstructBinaryTree(self, pre, tin):# write code hereif len(pre) == 0:return Noneroot = TreeNode(pre[0])pos = tin.index(pre[0]) #根節(jié)點在中序遍歷中的index,看作左子樹的節(jié)點個數(shù)root.left = self.reConstructBinaryTree( pre[1:1+pos], tin[:pos])root.right = self.reConstructBinaryTree( pre[pos+1:], tin[pos+1:])return root?
轉(zhuǎn)載于:https://www.cnblogs.com/yucen/p/9912044.html
總結(jié)
以上是生活随笔為你收集整理的【剑指Offer】16重建二叉树的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于mysql行级锁中MVCC的一些理解
- 下一篇: fiddler 看懂瀑布图Timelin