LeetCode | Unique Binary Search Trees II

来源:互联网 发布:自创网页软件 编辑:程序博客网 时间:2024/06/07 13:31

原文地址:http://blog.csdn.net/lanxu_yy/article/details/17504837

题目:

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.


思路:

类似http://blog.csdn.net/lanxu_yy/article/details/17504123,找到一个数作为根结点,剩余的数分别划入左子树或者右子树。

代码:


[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  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.        return createTree(1,n);  
  14.     }  
  15.       
  16.     vector<TreeNode *> createTree(int start, int end)  
  17.     {  
  18.         vector<TreeNode *> results;  
  19.         if(start>end)  
  20.         {  
  21.             results.push_back(NULL);  
  22.             return results;  
  23.         }  
  24.           
  25.         for(int k=start;k<=end;k++)  
  26.         {  
  27.             vector<TreeNode *> left = createTree(start,k-1);  
  28.             vector<TreeNode *> right = createTree(k+1,end);  
  29.             for(int i=0;i<left.size();i++)  
  30.             {  
  31.                 for(int j=0;j<right.size();j++)  
  32.                 {  
  33.                     TreeNode * root = new TreeNode(k);  
  34.                     root->left = left[i];  
  35.                     root->right = right[j];  
  36.                     results.push_back(root);  
  37.                 }  
  38.             }  
  39.         }  
  40.         return results;  
  41.     }  
  42. };  

0 0
原创粉丝点击