第四题:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
if not pre or not tin:
return None
root = TreeNode(pre[0])
root_id = tin.index(pre[0])
root.left = self.reConstructBinaryTree(pre[1:root_id+1], tin[:root_id])
root.right = self.reConstructBinaryTree(pre[root_id+1:], tin[root_id+1:])
return root
# write code here
Java:
/**
* 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 [] pre,int [] in) {
TreeNode root = helper(pre, 0, pre.length-1, in, 0, in.length-1);
return root;
}
public TreeNode helper(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn){
if(startPre > endPre || startIn > endIn){
return null;
}
//获取当前子树的根节点,即前序遍历startPre指针指向的节点
TreeNode root = new TreeNode(pre[startPre]);
//在中序遍历中找到当前根节点所在位子,则其左边为其左子树的节点中序遍历结果,右边为其右子树的节点中序遍历结果
for(int i=startIn; i<=endIn; i++){
if(in[i] == root.val){
//重构root的左子树
root.left = helper(pre, startPre+1, startPre+i-startIn, in, startIn, i-1);
//重构root的右子树
root.right = helper(pre, startPre+i-startIn+1, endPre, in, i+1, endIn);
}
}
return root;
}
}
/**
* 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 [] pre,int [] in) {
if((pre == null) || (in == null) || (pre.length==0) || (in.length==0)){
return null;
}
TreeNode root = new TreeNode(pre[0]);
int root_id = findIndex(in, pre[0]);
root.left = reConstructBinaryTree(getSubArr(pre, 1, root_id+1), getSubArr(in, 0, root_id));
root.right = reConstructBinaryTree(getSubArr(pre, root_id+1, pre.length), getSubArr(in, root_id+1, in.length));
return root;
}
public int findIndex(int[] arr, int val){
for(int i=0; i<arr.length; i++){
if(arr[i] == val)
return i;
}
return 0;
}
public int[] getSubArr(int[] arr, int start, int end){
if((end > arr.length) || (start > end))
return new int[0];
int[] subArr = new int[end - start];
for(int i=0; i < (end-start); i++){
subArr[i] = arr[start+i];
}
return subArr;
}
}