剑指OFFER 面试题7(二叉树):(前序/后序+中序)重建二叉树 (JAVA)

 

题目:

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},请重建二叉树并返回。

思路:

(1)首先根据根节点a将中序遍历划分为两部分,左边为左子树,右边为右子树

(2) 在左子树和右子树分布根据上述规则递归,得出左、右边子树。

package codingquestions;
import java.util.Arrays;

class BinaryTreeNode{
	int val;
	BinaryTreeNode left;
	BinaryTreeNode right;
	BinaryTreeNode(int x) {val=x;}
}

public class ReconstructBinaryTree {
	public static BinaryTreeNode reconstruct(int[] pre, int[] in) {
		if(pre==null || in==null) {return null;}
		if(pre.length==0 || in.length==0) {return null;}
		if(pre.length!=in.length) {return null;}
		//根据前序,确定根的值
		BinaryTreeNode root=new BinaryTreeNode(pre[0]);
		for(int i=0;i<in.length;i++) {
			if(root.val==in[i]) {
				root.left=reconstruct(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(in,0,i));
				root.right=reconstruct(Arrays.copyOfRange(pre, i+1, pre.length), Arrays.copyOfRange(in,i+1,in.length));				
			}
		}
		return root;	
	}
	//后序遍历打印二叉树
	public static void postprint(BinaryTreeNode head) {
		if (head==null) {return;}
		postprint(head.left);
		postprint(head.right);
		System.out.print(head.val+" ");		
		}
	
	//测试用例
	public static void main(String[] args) {
		int[] pre = {1,2,4,7,3,5,6,8};
		int[] in ={4,7,2,1,5,3,8,6};
		BinaryTreeNode root =reconstruct(pre, in);
		postprint(root);
	}
}
	

此外,还可以根据后序 {7,4,2,5,8,6,3,1} 和中序{4,7,2,1,5,3,8,6}结果来重建二叉树,并用前序打印出来。

package codingquestions;
import java.util.Arrays;


public class ReconstructBinaryTree1 {
	public static BinaryTreeNode reconstruct(int[] post, int[] in) {
		if(post==null || in==null) {return null;}
		if(post.length==0 || in.length==0) {return null;}
		if(post.length!=in.length) {return null;}
		//根据前序,确定根的值
		BinaryTreeNode root=new BinaryTreeNode(post[post.length-1]);
		for(int i=0;i<in.length;i++) {
			if(root.val==in[i]) {
				root.left=reconstruct(Arrays.copyOfRange(post, 0, i), Arrays.copyOfRange(in,0,i));
				root.right=reconstruct(Arrays.copyOfRange(post, i, post.length-1), Arrays.copyOfRange(in,i+1,in.length));				
			}
		}
		return root;	
	}
	//前序遍历打印二叉树
	public static void preprint(BinaryTreeNode head) {
		if (head==null) {return;}
		System.out.print(head.val+" ");	
		preprint(head.left);
		preprint(head.right);			
		}
	
	//测试用例
	public static void main(String[] args) {
		int[] pre = {7,4,2,5,8,6,3,1};
		int[] in ={4,7,2,1,5,3,8,6};
		BinaryTreeNode root =reconstruct(pre, in);
		preprint(root);
	}
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值