LeetCode : Unique Binary Search Tree

//先对n个数进行全排列,再对排列出来的每个结果进行判断是否为二叉搜索树(可以将排列结果作为二叉搜索树的先序遍历或者后续遍历)
//但这种方法在时间上超时
//正确方法应用用卡特兰数来解
import java.util.Scanner;

public class UniqueBinarySearchTree {
	int count = 0;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int numbers[] = new int[n];
		int i = 0;
		for (; i < n; i++) {
			int temp = scan.nextInt();
			System.out.println(temp);
			numbers[i] = temp;
		}
		System.out.println("i= " + i);
		UniqueBinarySearchTree ubst = new UniqueBinarySearchTree();
		ubst.binarysearch(numbers, 0, n);
		System.out.println("count=  " + ubst.count);
	}

	public void binarysearch(int num[], int start, int n) {
		if (start == n) {
			boolean result = isbinarysearchtree(num, n);
			if (result == true) {
				count++;
			}
			return;
		}

		for (int i = start; i < n; i++) {
			swap(num, i, start);
//			System.out.println(num[i] + " " + num[start]);
			binarysearch(num, start + 1, n);
			swap(num, i, start);
		}
	}

	public void swap(int num[], int a, int b) {
		int temp = num[a];
		num[a] = num[b];
		num[b] = temp;
	}

	public boolean isbinarysearchtree(int[] result, int n) {
		if (result == null || n == 0) {
			return false;
		}
		int root = result[n - 1];
		int i;
		for (i = 0; i < n-1; i++) {
			if (result[i] > root) {
				break;
			}
		}
		int j = i;
		for (; j < n-1; j++) {
			if (result[j] < root) {
				return false;
			}
		}
		boolean left = true;
//		System.out.println("i= "+i);
		if (i > 0) {
			left = isbinarysearchtree(result, i);
		}
		boolean right = true;
		if (i < n - 1) {
			right = isbinarysearchtree(Arrays.copyOfRange(result, i, n-1), n -i- 1);
		}
	
		return left&&right;
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值