首页 > 代码库 > Unique Binary Search Trees II

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

思路:使用递归来求解该问题。GenerateSub( start, end )生成[start,end]区间的所有二叉树。为了求解GenerateSub( start, end ),依次取i=start,start+1,...,end为根节点,则,其所有左子树由GenerateSub( start, i-1 )得到,所有右子树由GenerateSub( i+1, end )得到。

 1 class Solution { 2 public: 3     vector<TreeNode*> generateTrees( int n ) { 4         return GenerateSub( 1, n ); 5     } 6 private: 7     vector<TreeNode*> GenerateSub( int start, int end ) { 8         vector<TreeNode*> roots; 9         if( start > end ) { roots.push_back( 0 ); }10         for( int i = start; i <= end; ++i ) {11             vector<TreeNode*> left = GenerateSub( start, i-1 );12             vector<TreeNode*> right = GenerateSub( i+1, end );13             for( auto left_iter = left.begin(); left_iter != left.end(); ++left_iter ) {14                 for( auto right_iter = right.begin(); right_iter != right.end(); ++right_iter ) {15                     TreeNode *treeNode = new TreeNode( i );16                     treeNode->left = *left_iter;17                     treeNode->right = *right_iter;18                     roots.push_back( treeNode );19                 }20             }21         }22         return roots;23     }24 };