Leetcode: 95. Unique Binary Search Trees II

Description

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

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

思路

  • 回溯
  • 对每一个点,递归生成它的左子树和右子树

代码

/**
 * 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<TreeNode*> generateTrees(int n) {
        vector<TreeNode*> res;
        if(n == 0) return res;
        res = helper(1, n);
        
        return res;
    }
    
    vector<TreeNode*> helper(int start, int end){
        vector<TreeNode*> res;
        if(start > end){
            res.push_back(NULL);
        }
        else if(start == end){
            TreeNode *tmp = new TreeNode(start);
            res.push_back(tmp);
        }
        else{
            for(int i = start; i <= end; ++i){
                vector<TreeNode*> left = helper(start, i - 1);
                vector<TreeNode*> right = helper(i + 1, end);
                
                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];
                        res.push_back(root);
                    }
                }
            }
        }
        
        return res;
    }
};
posted @ 2017-06-22 09:30  JeffLai  阅读(135)  评论(0编辑  收藏  举报