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

leetcode[95]Unique Binary Search Trees II

时间:2015-02-09 14:03:20      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:

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

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
void creatTree(vector<TreeNode *> &res,int start, int end)
{
  if(start>end)
  {
      res.push_back(NULL);
      return;
  }
  for(int k=start;k<=end;k++)
  {
      vector<TreeNode *> left;
      vector<TreeNode *> right;
      creatTree(left,start,k-1);
      creatTree(right,k+1,end);
      for(int i=0;i<left.size();i++)
      {
          for(int j=0;j<right.size();j++)
          {
              TreeNode *root=new TreeNode(k);
              root->left=left[i];
              root->right=right[j];
              res.push_back(root);
          }
      }
  }
  return;
}
    vector<TreeNode *> generateTrees(int n) {
    vector<TreeNode *> res;
    creatTree(res,1,n);
    return res;
    }
};

 

leetcode[95]Unique Binary Search Trees II

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4281378.html

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