uva 548 Tree (根据中序遍历和后序遍历求先序遍历)

import java.util.Scanner;

public class Main {
	static Scanner scan = new Scanner(System.in);
	static int best_sum = 0;
	static int best = 0;
	public static void main(String[] args) {
		while(scan.hasNext()){
			String mid = scan.nextLine();
			String post = scan.nextLine();
			String[] aa = mid.split(" ");
			String[] bb = post.split(" ");
			int[] midOrder = new int[aa.length];
			int[] postOrder = new int[aa.length];
			for(int i=0;i<aa.length;i++){
				midOrder[i] = Integer.parseInt(aa[i]);
				postOrder[i] = Integer.parseInt(bb[i]);
			}
			
			Node root = build(midOrder,postOrder,0,midOrder.length-1,0,postOrder.length-1);
			best_sum = Integer.MAX_VALUE;
			best = Integer.MAX_VALUE;
			Pre(root,0);
			System.out.println(best);
		}
	}
	//先序递归求最优解
	public static void Pre(Node root,int sum){
		if(root!=null){
			sum+=root.value;
			if(root.left==null&&root.right==null){
				if(sum<best_sum||(sum==best_sum&&root.value<best)){
					best_sum = sum;
					best = root.value;
				}
			}
			if(root.left!=null)Pre(root.left,sum);
			if(root.right!=null)Pre(root.right,sum);
		}
		
	}
	
	//根据中序和后序建树
	public static Node build(int[] m,int[] p,int m1,int m2,int p1,int p2){
		if(m1>m2||p1>p2)return null;
		Node root = new Node();
		int v = p[p2];
		root.value = v;
		int rootIndex = 0;
		while(m[rootIndex]!=v)rootIndex++;
		int cnt = rootIndex-m1;
		root.left = build(m,p,m1,rootIndex-1,p1,p1+cnt-1);
		root.right = build(m,p,rootIndex+1,m2,p1+cnt,p2-1);
		return root;
	}
	
	static class Node{
		int value;
		Node left,right;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值