二叉树的构建必须拥有中序遍历(中序+前序,中序+后序)才可以唯一构建成功。
采用递归的方式建立二叉树,前序遍历为{1,2,4,7,3,5,6,8},中序遍历为{4,7,2,1,5,3,8,6},由前序遍历可知根节点为1,在中序遍历中找到1的位置,1之前的为根节点的左子树,1之后的为根节点的右子树;在前序遍历中,左子树的元素为2,4,7,所以1的左节点为2,再对应中序遍历中,2左边有4,7,右边没有元素,所以4,7为2的左子树,以此递推。
递归式:build(中序遍历数组,中序遍历左端,中序遍历右端,前序遍历数组,前序遍历左端,前序遍历右端)
设前序遍历的第一个元素为pre[preleft],该元素在中序遍历中为in[i];
左子树递归式:build(in,inleft,i-1,pre,preleft+1,preleft+i-inleft);
右子树递归式:build(in,i+1,inright,pre,preleft+i-inleft+1,preright);
public class Main1 {
public static class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val=x;
}
}
public static void main(String[] args) {
int[] in=new int[] {4,7,2,1,5,3};
int[] pre=new int[] {1,2,4,7,3,5};
TreeNode root=build(in,0,in.length-1,pre,0,pre.length-1);
bianli(root);
}
public static void bianli(TreeNode root) {
if(root==null) {
return ;
}
bianli(root.left);
System.out.println(root.val);
bianli(root.right);
}
public static TreeNode build(int[] in,int inleft,int inright,int[] pre, int preleft,int preright) {
if(inleft>inright||preleft>preright) {
return null;
}
TreeNode root=new TreeNode(pre[preleft]);
for(int i=inleft;i<=inright;i++) {
if(in[i]==pre[preleft]) {
root.left=build(in,inleft,i-1,pre,preleft+1,preleft+i-inleft);
root.right=build(in,i+1,inright,pre,preleft+i-inleft+1,preright);
}
}
return root;
}
}