设为首页 加入收藏

TOP

经典中的经典Unique Binary Search Trees II
2015-11-21 00:56:46 来源: 作者: 【 】 浏览:1
Tags:经典 Unique Binary Search Trees

?

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
迄今为止看到的最为经典的算法,分数超过14000的好评 最经典的解法:

?

/**
 * 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
  
    generateTrees(int n) {
        return helper(1, n);
    }
    vector
   
     helper(int s, int e){ if(s>e){ return vector
    
     (1, NULL); } vector
     
       res; for(int i=s; i<=e; i++){ vector
      
        left=helper(s, i-1); vector
       
         right=helper(i+1, e); for(int j=0; j
        
         left=left[j]; p->right=right[k]; res.push_back(p); } } } return res; } };
        
       
      
     
    
   
  
?
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu4800_Josephina and RPG(二维.. 下一篇HDU 1074 Doing Homework(状压dp..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: