【LeetCode】95. Unique Binary Search Trees II

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

 

由于1~n是升序列,因此建起来的树天然就是BST。

递归思想,依次选择根节点,对左右子序列再分别建树。

由于左右子序列建树的结果也可能不止一种,需要考虑所有搭配情况。

vector<TreeNode *> left代表所有valid左子树。

vector<TreeNode *> right代表所有valid右子树。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<TreeNode *> generateTrees(int n) {
        return Helper(1, n);
    }
    vector<TreeNode *> Helper(int begin, int end)
    {
        vector<TreeNode *> ret;
        if(begin > end)
            ret.push_back(NULL);
        else if(begin == end)
        {
            TreeNode* node = new TreeNode(begin);
            ret.push_back(node);
        }
        else
        {
            for(int i = begin; i <= end; i ++)
            {//root
                vector<TreeNode *> left = Helper(begin, i-1);
                vector<TreeNode *> right = Helper(i+1, end);
                for(int l = 0; l < left.size(); l ++)
                {
                    for(int r = 0; r < right.size(); r ++)
                    {
                        //new tree
                        TreeNode* root = new TreeNode(i);
                        root->left = left[l];
                        root->right = right[r];
                        ret.push_back(root);
                    }
                }
            }
        }
        return ret;
    }
};

posted @ 2014-12-02 20:02  陆草纯  阅读(2722)  评论(0编辑  收藏  举报