[leetcode] Unique Binary Search Trees II 解题报告

题目链接:https://leetcode.com/problems/unique-binary-search-trees-ii/

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

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

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

递归构造左右子树。比较困难的是如何存储每一棵树。递归的产生每一个子树的左右节点,构造当前节点,最后可以的得到完整的一棵树。当前i节点的左节点可以是(1,i-1)的所有节点,同样右节点可以是(i+1, n)的所有节点,因此枚举所有的左右节点的可能值,最终得到所有的树。

具体代码如下:

/**
 * 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:
    void DFS(int start, int end, vector<TreeNode*>& tree)
    {
        if(start > end)
        {
            tree.push_back(NULL);
            return;
        }
        for(int i = start; i<= end; i++)
        {
            vector<TreeNode*> left;
            vector<TreeNode*> right;
            DFS(start, i-1, left);
            DFS(i+1, end, right);
            for(int j = 0; j< left.size(); j++)
            {
                for(int k =0; k < right.size(); k++)
                {
                    TreeNode* root = new TreeNode(i);
                    root->left = left[j];
                    root->right = right[k];
                    tree.push_back(root);
                }
            }
        }
    }
    
    vector<TreeNode*> generateTrees(int n) {
        vector<TreeNode*> tree;
        DFS(1, n, tree);
        return tree;
    }
};


参考:http://yucoding.blogspot.com/2013/05/leetcode-question115-unique-binary.html

你可能感兴趣的:(LeetCode,算法,动态规划)