此題目對應於
105. Construct Binary Tree from Preorder and Inorder Traversal 和 106. Construct Binary Tree from Inorder and Postorder Traversal
題目要求:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
這裏必須給出兩個遍歷纔可以重建二叉樹,其中前序或者後續的遍歷能給出樹根節點的值,
中序遍歷起到劃分二叉樹左右子樹的作業。
距離說明:輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建出如下圖所示的二叉樹並輸出它的頭結點。
解題思路:
根據先序向量數組的值把中序向量數組一分爲二,然後遞歸左右部分;
在二叉樹的前序遍歷和中序遍歷的序列中確定根結點的值、左子樹結點的值和右子樹結點的值的步驟如下圖所示:
下面給出Python代碼:
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
'''
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。
例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
'''
class Solution(object):
# 根據前序和中序遍歷重建二叉樹
def buildTree(self, preorder, inorder):
if len(preorder)==0:
return None
if len(preorder)==1:
return TreeNode(preorder[0])
root_val = preorder[0]
idx = inorder.index(root_val)
root = TreeNode(root_val)
root.left = self.buildTree(preorder[1:idx+1],inorder[:idx])
root.right = self.buildTree(preorder[idx+1:],inorder[idx+1:])
return root
# 根據後序和中序遍歷重建二叉樹
def buildTree(self, inorder, postorder):
if len(inorder)==0:
return None
if len(inorder)==1:
return TreeNode(inorder[0])
root_v = postorder[-1]
root = TreeNode(root_v)
idx = inorder.index(root_v)
root.left = self.buildTree(inorder[:idx],postorder[:idx])
root.right = self.buildTree(inorder[idx+1:],postorder[idx:-1])
return root
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
參考文獻:
http://www.cnblogs.com/edisonchou/p/4741099.html