只要求个数,递推根节点分割左右子树即可
class Solution { public int numTrees(int n) { int []dp=new int[n+1]; for(int i=1;i<=n;i++){ if(i==1||i==2) dp[i]=i; else{ for(int j=1;j<=i;j++) if(j>1&&j<i)//有左子树和右子树 dp[i]+=dp[j-1]*dp[i-j]; else if(j==1)//只有右子树 dp[i]+=dp[i-j]; else dp[i]+=dp[j-1]; } } return dp[n]; } }
要求求具体的树,还是同上思想
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<TreeNode> generateTrees(int n) { if(n == 0) return new LinkedList<TreeNode>(); return generateTrees(1,n); } public List<TreeNode> generateTrees(int start,int end) { List<TreeNode> res = new LinkedList<TreeNode>(); if(start > end){ res.add(null); return res; } for(int i = start;i <= end;i++){ List<TreeNode> subLeftTree = generateTrees(start,i-1); List<TreeNode> subRightTree = generateTrees(i+1,end); for(TreeNode left : subLeftTree){ for(TreeNode right : subRightTree){ TreeNode node = new TreeNode(i); node.left = left; node.right = right; res.add(node); } } } return res; } }
原文地址:https://www.cnblogs.com/yuelien/p/10592940.html
时间: 2024-11-08 21:43:30