劍指Offer 重建二叉樹

2021-10-02 14:07:12 字數 1072 閱讀 8983

# -*- coding:utf-8 -*-

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class

solution

:# 返回構造的treenode根節點

defreconstructbinarytree

(self, pre, tin)

:# write code here

iflen

(pre)==0

:return

none

iflen

(pre)==1

:return treenode(pre[0]

) root = treenode(pre[0]

)#pre[1:tin.index(pre[0])+1 ] = [1:4] 是找先序遍歷的左子樹 2 4 7

#tin[:tin.index(pre[0])] = [0:3] = [4,7,2]

#遞迴迴圈下去 得到乙個左子樹鏈結在root上 就得到了完整的左子樹

root.left = self.reconstructbinarytree(pre[

1:tin.index(pre[0]

)+1]

,tin[

:tin.index(pre[0]

)])#pre[tin.index(pre[0])+1:] = [4:8]= [ 5,3,8,6] 先序遍歷的右子樹

#tin[tin.index[pre[0])+1:]) = [4:8] = [3,5,6,8] 中序遍歷的右子樹

#同上 root.right = self.reconstructbinarytree(pre[tin.index(pre[0]

)+1:

],tin[tin.index(pre[0]

)+1:

])return root

劍指offer 重建二叉樹

重建二叉樹2.cpp 定義控制台應用程式的入口點。題目描述 輸入乙個二叉樹的前序遍歷和中序遍歷,輸出這顆二叉樹 思路 前序遍歷的第乙個節點一定是這個二叉樹的根節點,這個節點將二叉樹分為左右子樹兩個部分,然後進行遞迴求解 include stdafx.h include vector using na...

《劍指offer》重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如,則重建二叉樹並返回。輸入乙個樹的前序和中序,例如輸入前序遍歷序列和中序遍歷序列 根據輸入的前序和中序,重建乙個該二叉樹,並返回該樹的根節點。definition for binary...

劍指offer 重建二叉樹

題目描述 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。definition for binary tree struct treenode class solution if ...