import java.util.*;
/**
* @author : xfhy
* Create time : 2020年8月6日10:52:21
* Description : 96. 不同的二叉搜索树
* source : https://leetcode-cn.com/problems/unique-binary-search-trees/
*/
public class Solution {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
/**
* 概念: 二叉搜索树关键的性质是根节点的值大于左子树所有节点的值,小于右子树所有节点的值,且左子树和右子树也同样为二叉搜索树。
*/
/**
* 思路: 这是一个公式: C = C * 2 * (2 * i + 1) / (i + 2);
* https://leetcode-cn.com/problems/unique-binary-search-trees/solution/bu-tong-de-er-cha-sou-suo-shu-by-leetcode-solution/
*/
public static int numTrees(int n) {
// 提示:我们在这里需要用 long 类型防止计算过程中的溢出
long C = 1;
for (int i = 0; i < n; ++i) {
C = C * 2 * (2 * i + 1) / (i + 2);
}
return (int) C;
}
public static TreeNode createBinaryTree(LinkedList<Integer> inputList) {
if (inputList == null || inputList.isEmpty()) {
return null;
}
TreeNode node = null;
Integer data = inputList.removeFirst();
if (data != null) {
node = new TreeNode(data);
node.left = createBinaryTree(inputList);
node.right = createBinaryTree(inputList);
}
return node;
}
public static void main(String[] args) {
/*LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(5, 4, 11, 7, null, null, 2, null, null, null, 8, 13, null, null, 4,
5, null, null, 1));*/
/*LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(3, 2, 9, null, null, 10, null,
null, 8, null, 4));*/
LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(3, 9, null, null, 20, 15, null, null, 7));
TreeNode binaryTree = createBinaryTree(integers);
System.out.println(numTrees(19));
}
}