【LeetCode】Unique Binary Search Trees II

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

题解:给出一个序列的所有BST集合,本题可以用递归或dp解决,递归主要转化为子问题,因为要保证bst所以从一个递增序列进行分割,每次从1到n找一个数k然后分成左右两个子树,只需新建k节点两个子树递归解决

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector generateTrees(int n) {
        if(n==0) return vector();
        return dfs(1,n);
    }
    vector dfs(int st,int ed){
        vector res;
        if(st>ed) {
            res.push_back(nullptr);
            return res;
        }
        for(int k=st;k<=ed;k++)
        {
            vector ll=dfs(st,k-1);
            vector lr=dfs(k+1,ed);
            for(int i=0;ileft=ll[i];
                    root->right=lr[j];
                    res.push_back(root);
                }
        }
        return res;
    }
};

 

你可能感兴趣的:(DFS,二叉树)