码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Unique Binary Search Trees II

时间:2014-12-02 20:38:19      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

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。

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

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

/**
 * 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) {
        vector<TreeNode *> res;
        if(n == 0)
        {
            res.push_back(NULL);
            return res;
        }
        else 
        {
            return Helper(1, n);
        }
    }
    vector<TreeNode*> Helper(int begin, int end)
    {
        vector<TreeNode*> res;
        if(begin > end)
        {
            res.push_back(NULL);
            return res;
        }
        else if(begin == end)
        {
            TreeNode* root = new TreeNode(begin);
            res.push_back(root);
            return res;
        }
        else
        {
            for(int i = begin; i <= end; i ++)
            {
                //tag
                vector<TreeNode*> left = Helper(begin, i-1);
                vector<TreeNode*> right = Helper(i+1, end);
                for(int l = 0; l < left.size(); l ++)
                {//all BST in left
                    for(int r = 0; r < right.size(); r ++)
                    {//all BST in right
                        //new root here! not the tag position.
                        TreeNode* root = new TreeNode(i);
                        root->left = left[l];
                        root->right = right[r];
                        res.push_back(root);
                    }
                }
                
            }
            return res;
        }
    }
};

bubuko.com,布布扣

【LeetCode】Unique Binary Search Trees II

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/ganganloveu/p/4138344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!