Building Heap

题目1 : Building Heap

时间限制:10000ms

单点时限:1000ms

内存限制:256MB

描述

Given an array A1, A2, ... AN, your task is to build a binary treee T which satisfies the following requirments:  

1. T is a min-heap;  

2. The inorder traversal sequence of T is A1, A2, ... AN.  

For example if the array is 3, 2, 8, 1, 4, 7, the tree is as below:  

          1
         / \
        2   4
       / \   \
      3   8   7

输入

The first line contain an integer N denoting the array length. (1 <= N <= 100)  

The second line contains N distinct integers denoting A1, A2, ... AN. (1 <= Ai <= 1000000)

输出

Output the preorder traversal sequence of T.

样例输入

6  
3 2 8 1 4 7

样例输出

1 2 3 8 4 7

这道题也是类似,堆的性质可以让我们确定最小的元素一定是根,比如在样例中1一定是根。

然后根据中序遍历的顺序,1左边的一定是左子树部分,1右边的一定是右子树的部分。

左右子树都可以递归求解。


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        final int N = scanner.nextInt();
        int[] arr = new int[N];
        for (int i = 0; i < N; i++) {
        	arr[i] = scanner.nextInt();
        }
        TreeNode root = solve(arr, N);
        preorderTraversal(root);
        scanner.close();
    }
    
    private static TreeNode solve(int[] arr, int N) {
    	TreeNode root = constructTree(arr, 0, N - 1);
    	return root;
    }
    
    private static TreeNode constructTree(int[] arr, int lo, int hi) {
    	if (lo > hi) return null;
    	
    	// find minimum
    	int minIndex = 0;
    	int min = Integer.MAX_VALUE;
    	for (int i = lo; i <= hi; i++) {
    		if (arr[i] < min) {
    			min = arr[i];
    			minIndex = i;
    		}
    	}
    	
    	TreeNode root = new TreeNode(min);
    	root.left = constructTree(arr, lo, minIndex - 1);
    	root.right = constructTree(arr, minIndex + 1, hi);
    	return root;
    }
    
    private static void preorderTraversal(TreeNode root) {
    	if (root == null) return;
    	System.out.print(root.val + " ");
    	preorderTraversal(root.left);
    	preorderTraversal(root.right);
    }
    
    public static class TreeNode {
    	int val;
    	TreeNode left;
    	TreeNode right;
    	
    	TreeNode(int x) {
    		val = x;
    	}
    }

}
import java.util.Scanner;
public class Main {
	static void help(int[] nums,int l,int  r){
		int k=l;
		for (int i=l+1;i<=r;i++){
			if(nums[k]>nums[i]){
				k = i;
			}
		}
		System.out.print(nums[k]+" ");
		if(l<k)help(nums, l, k-1);
		if(k<r)help(nums, k+1, r);
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int a = in.nextInt();
		int[] nums = new int[a];
		for (int i = 0; i < a; i++) {
			nums[i] = in.nextInt();
		}
		help(nums, 0, nums.length-1);
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_38970751/article/details/85698342
今日推荐