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

95.Unique Binary Search Trees II

时间:2015-11-30 20:24:50      阅读:135      评论: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.

思路:DFS。取i作为根节点,递归求1->i-1 i+1->n的二叉搜索树,置于 vector<TreeNode *> left vector<TreeNode *> right 之中,然后取i作为根节点,组合数组leftright,分别取一个元素作为root的左右子树,然后将组合之后的树置于result之中,最后返回result即可。注意一个特殊情况,当start>end,将空节点写入result,返回result,代表返回一个空节点。还有就是初始n<1的特殊处理。

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. vector<TreeNode*> generateTrees(int n) {
  13. if(n<1){
  14. vector<TreeNode *> result;
  15. return result;
  16. }
  17. return help(1,n);
  18. }
  19. vector<TreeNode *> help(int start,int end){
  20. vector<TreeNode *> result;
  21. if(start>end){
  22. result.push_back(NULL);
  23. return result;
  24. }
  25. for(int i=start;i<=end;i++){
  26. vector<TreeNode *> left =help(start,i-1);
  27. vector<TreeNode *> right=help(i+1,end);
  28. for(int j=0;j<left.size();j++){
  29. for(int k=0;k<right.size();k++){
  30. TreeNode *root =new TreeNode(i);
  31. root->left=left[j];
  32. root->right=right[k];
  33. result.push_back(root);
  34. }
  35. }
  36. }
  37. return result;
  38. }
  39. };











95.Unique Binary Search Trees II

标签:

原文地址:http://www.cnblogs.com/zhoudayang/p/5008037.html

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