前序:ABCDEF
中序:CBAEDF
求原来的二叉树
前序:根左右
中序:左根右
后序:左右根
根据前序和中序还原二叉树:
思路:根据前序知道二叉树的根包括各个子树的根,然后再在中序里面找到根的那个,前面的都是左子树,而后面的都是右子树,然后用递归的思想再处理每个子树的那部分。思路还是一样的。
部分代码;
代码说明:代码取自牛客网 欲风
package com.xaut.jianzhioffer;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x){
this.val = x;
}
}
-----------------------------------
package com.xaut.jianzhioffer;
/*
* 根据二叉树的先序和中序重新构建二叉树
* 前序:pre[]
* 中序:in[]
* public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x){
this.val = x;
}
*}
* */
public class CreateTree {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode root = createTree(pre,0,pre.length-1,in,0,in.length-1);
return root;
}
private TreeNode createTree(int[] pre, int startpre, int endpre, int[] in, int startin, int endin) {
// TODO Auto-generated method stub
if(startpre>endpre || startin>endin){
return null;
}
TreeNode root = new TreeNode(pre[startpre]);//树的根
for(int i = startin;i<=endin;i++){
if(pre[startpre] == in[i]){
root.left = createTree(pre,startpre+1,startpre+i,in,startin,i-1);//去除掉已经确定的根节点
root.right = createTree(pre,i-startin+startpre+1,endpre,in,i+1,endin);
//说明:i-startin 是i这个元素的左子树 解释来自 深水的鱼
}
}
return root;
}
}