Loading

不同的二叉搜索树&II

不同的二叉搜索树

只要求个数,递推根节点分割左右子树即可

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];
    }
}

不同的二叉搜索树 II

要求求具体的树,还是同上思想

/**
 * 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>();
        else return generateTrees(1,n);
    }
    public List<TreeNode> generateTrees(int begin,int end){
        List<TreeNode>res=new LinkedList<>();
        if(begin>end) {
            res.add(null);
            return res;
        }
        for(int i=begin;i<=end;i++) {
            List<TreeNode>leftSubList=generateTrees(begin,i-1);
            List<TreeNode>rightSubList=generateTrees(i+1,end);
            for(TreeNode left:leftSubList) {
                for(TreeNode right:rightSubList) {
                    TreeNode p=new TreeNode(i);
                    p.left=left;
                    p.right=right;
                    res.add(p);
                }
            }
        }
        return res;
    }
}

 

 

posted @ 2019-03-25 11:58  ArkiWang  阅读(521)  评论(0编辑  收藏  举报