题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
分析
1、二叉树的前序遍历序列一定是该树的根节点
2、中序遍历序列中根节点前面一定是该树的左子树,后面是该树的右子树
Java版本1
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] preOrder,int [] inOrder) {
int preLength = preOrder.length;
int inLength = inOrder.length;
if(preLength == 0 && inLength == 0)
return null;
return reConstructBinaryTree(preOrder, inOrder, 0, preLength - 1, 0, inLength - 1);
}
private TreeNode reConstructBinaryTree(int[] preOrder, int[] inOrder, int pStart, int pEnd, int iStart, int iEnd) {
TreeNode root = new TreeNode(preOrder[pStart]);
if(pStart == pEnd && iStart == iEnd)
return root;
//在中序序列中找到根结点
int rootIndex = 0;
for(rootIndex = iStart; rootIndex < iEnd; rootIndex ++) {
if(preOrder[pStart] == inOrder[rootIndex])
break;
}
//划分左右子树
int leftLength = rootIndex - iStart;
int rightLength = iEnd - rootIndex;
if(leftLength > 0)
root.left = reConstructBinaryTree(preOrder, inOrder, pStart + 1, pStart + leftLength , iStart, rootIndex - 1 );
if(rightLength > 0)
root.right = reConstructBinaryTree(preOrder, inOrder, pStart + leftLength + 1, pEnd, rootIndex + 1, rootIndex + rightLength );
return root;
}
}
Java版本2
/**
*
* Definition for binary tree
3
* public class TreeNode {
4
* int val;
* TreeNode left;
6
* TreeNode right;
7
* TreeNode(int x) { val = x; }
8
* }
9
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] preOrder,int [] inOrder) {
int preLength = preOrder.length;
int inLength = inOrder.length;
if(preLength == 0 && inLength == 0)
return null;
return reConstructBinaryTree(preOrder, inOrder, 0, preLength - 1, 0, inLength - 1);
}
private TreeNode reConstructBinaryTree(int[] preOrder, int[] inOrder, int pStart, int pEnd, int iStart, int iEnd) {
if(pStart > pEnd || iStart > iEnd)
return null;
//在中序序列中找到根结点
TreeNode root = new TreeNode(preOrder[pStart]);
for(int rootIndex = iStart; rootIndex <= iEnd; rootIndex ++) {
if(preOrder[pStart] == inOrder[rootIndex]){
//划分左右子树
root.left = reConstructBinaryTree(preOrder, inOrder, pStart + 1, pStart + rootIndex - iStart, iStart, rootIndex - 1 );
root.right = reConstructBinaryTree(preOrder, inOrder, rootIndex - iStart + pStart + 1, pEnd, rootIndex + 1, iEnd );
}
}
return root;
}
}
Python版本
# -*- 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
elif len(pre) == 1:
return TreeNode(pre[0])
else:
root = TreeNode(pre[0])
root.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0]) + 1], tin[:tin.index(pre[0])])
root.right = self.reConstructBinaryTree(pre[tin.index(pre[0]) + 1:], tin[tin.index(pre[0]) + 1:])
return root