LeetCode 95. Unique Binary Search Trees II

2020-01-15 17:58:00 浏览数 (1)

题目

DFS,

代码语言:javascript复制
class Solution {
public:
    int vis[100005];
    int m;
    vector<TreeNode*> generateTrees(int n) {
        vector<TreeNode*> ans;
        if(n==0)
            return ans;
        return fun(1,n);
    }

    vector<TreeNode*> fun(int l,int r)
    {
        vector<TreeNode*> result;
        for(int i=l;i<=r;i  )
        {
            vector<TreeNode*> lefts = fun(l,i-1);
            vector<TreeNode*> rights = fun(i 1,r);

            for(int j=0;j<lefts.size();j  )
            {
                for(int k=0;k<rights.size();k  )
                {
                    TreeNode* tree = new TreeNode(i);
                    tree->left = lefts[j];
                    tree->right = rights[k];

                    result.push_back(tree);
                }
            }
        }
        if(result.size()==0)
        {
            result.push_back(NULL);
        }

        return result;

    }
};
dfs

0 人点赞