[Leetcode] 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

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


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / 
 2   3
    /
   4
    
     5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".

 题中很重要的一点是,各个结点的值是递增的,即非降型。所以,对任一点,其前的点构成二叉树的左子树,其后点构成二叉树右子树。可以从这两部分中随意的选取一部分组成子二叉树的左右子树。递归方法的思路是,遍历这n个数,然后从当前数的前后部分选取、组合成新的二叉树。终止条件是beg>end。感觉很哄哄的思想-水中的鱼的博客,用指针及堆来存储变量。

 1 /**
 2  * Definition for binary tree
 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     {
14         return creatTre(1,n);
15     }
16 
17     vector<TreeNode *> creatTre(int beg,int end)
18     {
19         vector<TreeNode *> res;
20         if(beg>end)
21         {
22             res.push_back(NULL);
23             return res;
24         }
25         for(int k=beg;k<=end;++k)
26         {
27             //求根节点i的左右子树集合
28             vector<TreeNode *> lTree=creatTre(beg,k-1);
29             vector<TreeNode *> rTree=creatTre(k+1,end);
30 
31             /*将左右子树相互匹配,每一个左子树都与所有右子树匹配,
32             *每一个右子树都与所有的左子树匹配  */
33             for(int i=0;i<lTree.size();++i)
34                 for(int j=0;j<rTree.size();++j)
35                 {
36                     TreeNode *root=new TreeNode(k);
37                     root->left=lTree[i];
38                     root->right=rTree[j];
39                     res.push_back(root);
40                 }
41         }
42         return res;
43     }
44 };
原文地址:https://www.cnblogs.com/love-yh/p/7003324.html