剑指offer第五天之重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
java:
int[] array = {1, 2, 3, 4, 5};
int[] arrayCopy = Arrays.copyOfRange(array, 0,3);
System.out.println(Arrays.toString(arrayCopy)); //[1, 2, 3]
import java.util.Arrays;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in)
{
if(pre.length==0)
return null;
int rootval = pre[0];
//数组长度仅为1的时候就要处理
if(pre.length==1)
return new TreeNode(rootval);
TreeNode root = new TreeNode(rootval);
int rootIndex = 0;
//我们先找到root所在的位置,确定好前序和中序中左子树和右子树序列的范围
for(int i=0;i<in.length;i++)
{
if (in[i]==rootval)
{
rootIndex =i;
break;
}
}
//递归,假设root的左右子树都已经构建完毕,那么只要将左右子树安到root左右即可
//这里注意Arrays.copyOfRange(int[],start,end)是[)的区间
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,rootIndex+1),Arrays.copyOfRange(in,0,rootIndex));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,rootIndex+1,pre.length),Arrays.copyOfRange(in,rootIndex+1,in.length));
return root;
}
}
python:
lista =[1, 4, 9, 16, 25]
print(lista[:3])
print(lista[3+1:])
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin:
return None
root = TreeNode(pre.pop(0))
index = tin.index(root.val)
root.left = self.reConstructBinaryTree(pre, tin[:index])
root.right = self.reConstructBinaryTree(pre, tin[index + 1:])
return root
c++:
#include<iostream>
#include<string>
using namespace std;
typedef struct TreeNode{
char data;
struct TreeNode *lchild;
struct TreeNode *rchild;
}*bitree;
void inorder(bitree root)
{
if(root!=NULL)
{
inorder(root->lchild);
inorder(root->rchild);
cout<<root->data;
}
}
TreeNode *create_tree(string p,string m)
{
bitree bt=new(TreeNode);
if(p.length()==0||m.length()==0)
{
return NULL;
}
else
{
bt->data=p[0];
int index=m.find(p[0]);
bt->lchild=create_tree(p.substr(1,index),m.substr(0,index));
bt->rchild=create_tree(p.substr(index+1),m.substr(index+1));
return bt;
}
}
int main()
{
bitree *bt;
bt=new(bitree);
string p,m;
cin>>p>>m;
*bt=create_tree(p,m);
inorder(*bt);
return 0;
}