本文主要是介绍LeetCode--96. Unique Binary Search Trees 95. Unique Binary Search Trees II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
96. Unique Binary Search Trees
求第n个卡特兰数
class Solution {public int numTrees(int n) {int[] dp=new int[n+1];dp[0]=1;dp[1]=1;for(int i=2;i<=n;i++){for(int root=1;root<=i;root++){dp[i]+=dp[root-1]*dp[i-root];}}return dp[n];}
}
95. Unique Binary Search Trees II
class Solution {public List<TreeNode> generateTrees(int n) {if(n==0)return new LinkedList<TreeNode>();return buildTree(1,n);}public static LinkedList<TreeNode> buildTree(int min,int max){LinkedList<TreeNode> res=new LinkedList<>();if(min>max){res.add(null);return res;}for(int i=min;i<=max;i++){LinkedList<TreeNode> leftSubTrees=buildTree(min,i-1);LinkedList<TreeNode> rightSubTrees=buildTree(i+1,max);if(leftSubTrees.size()==0 && rightSubTrees.size()==0){TreeNode root=new TreeNode(i);res.add(root);}else if(leftSubTrees.size()==0){for(TreeNode node:rightSubTrees){TreeNode root=new TreeNode(i);root.right=node;res.add(root);}}else if(rightSubTrees.size()==0){for(TreeNode node:rightSubTrees){TreeNode root=new TreeNode(i);root.left=node;res.add(root);}}else{for(TreeNode leftNode:leftSubTrees){for(TreeNode rightNode:rightSubTrees){TreeNode root=new TreeNode(i);root.left=leftNode;root.right=rightNode;res.add(root);}}}}return res; }}
这篇关于LeetCode--96. Unique Binary Search Trees 95. Unique Binary Search Trees II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!