UVA 548 Tree (first-order traversal based on sequence traversal and sequential traversal) _uva

Source: Internet
Author: User
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);
			}///First order recursive optimal solution 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); }///based on the sequence and subsequent achievements public static Node build (int[] m,int[] p,int m1,int m2,int p1,int p2) {if m1>m2| |
		P1&GT;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; }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.