根据中序和前序遍历结果构建二叉树

二叉树的构建必须拥有中序遍历(中序+前序,中序+后序)才可以唯一构建成功。
采用递归的方式建立二叉树,前序遍历为{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;
		
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值