题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如:前序遍历序列{ 1, 2, 4, 7, 3, 5, 6, 8}和中序遍历序列{4, 7, 2, 1, 5, 3, 8,6},重建出下图所示的二叉树并输出它的头结点。
思路:
前序序列:【1 2 4 7 3 5 6 8】 中序序列:【4 7 2 1 5 3 8 6】
从前序遍历序列观察到根节点为1,结合中序序列得到:
左子树元素:【4 7 2 1】 右子树元素:【5 3 8 6】
左子树:前序遍历序列:【2 4 7】 中序遍历序列:【4 7 2】
右子树:前序遍历序列:【3 5 6 8】 中序遍历序列:【5 3 8 6】
然后根据左子树的前序遍历序列和中序遍历序列重复上述操作;
然后根据右子树的前序遍历序列和中序遍历序列重复上述操作;
代码参考:
1、定义二叉树树节点
class TreeNode{
public int value;
public TreeNode leftChild;
public TreeNode rightChild;
public TreeNode(int value) this.value = value;
}
2、定义核心函数
public TreeNode construct(int[] preOrder, int[] inOrder){
if(preOrder == null || preOrder.length == 0 || inOrder == null || inOrder.length == 0) return null;
return construct(preOrder,0,preOrder.length - 1,inOrder,0,inOrder.length - 1);
}
public TreeNode construct(int[] preOrder,int ps,int pe,int[] inOrder ,int is,int ie){
if(ps > pe || is > ie) return null;
//获取根节点
int value= preOrder[ps];
int index = is;
//创建结点
TreeNode node = new TreeNode(value);
//从中序序列查找等于index的序号
while(index < ie && inOrder[index] != value)index ++;
if(index > ie) throw new RuntimeException("Input error!");
//左孩子
node.leftChild = construct(preOrder , ps + 1 , ps + index - is , inOrder, is, index - 1);
//右孩子
node.rightChild = construct(preOrder,ps + index - is + 1 , pe,inOrder, index + 1, ie);
return node;
}
参考文章:https://blog.csdn.net/derrantcm/article/details/45457557