題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
思路:根據中序遍歷和前序遍歷可以確定二叉樹,具體過程爲:
1、根據前序序列第一個結點確定根結點;
2、根據根結點在中序序列中的位置分割出左右兩個子序列;
3、對左子樹和右子樹分別遞歸使用同樣的方法繼續分解
例如:
前序序列{1,2,4,7,3,5,6,8} = pre
中序序列{4,7,2,1,5,3,8,6} = in
1、根據當前前序序列的第一個結點確定根結點,爲 1,找到 1 在中序遍歷序列中的位置,爲 in[3];
2、切割左右子樹,則 in[3] 前面的爲左子樹, in[3] 後面的爲右子樹,則切割後的左子樹前序序列爲:{2,4,7},切割後的左子樹中序序列爲:{4,7,2};切割後的右子樹前序序列爲:{3,5,6,8},切割後的右子樹中序序列爲:{5,3,8,6};
3、對子樹分別使用同樣的方法分解
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 here0
if len(pre)==0:
return None
if len(pre)==1:
return TreeNode(pre[0])
root=TreeNode(pre[0])
tinL=tin[:tin.index(pre[0])]
tinR=tin[tin.index(pre[0])+1:]
root.left=self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tinL)
root.right=self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tinR)
return root