Classic Unique Binary Search Trees II

Source: Internet
Author: User

Classic Unique Binary Search Trees II
 

Unique Binary Search Trees II

Original question:

Given n, generate all structurally unique BST's (binary search trees) that store values 1... n.

For example,
Given n = 3, your program shocould return all 5 unique BST's shown below.

   1         3     3      2      1           /     /      /            3     2     1      1   3      2    /     /                           2     1         2                 3
The most classic algorithm we have seen so far, the most popular solution with a score of over 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; }};
       
      
     
    
   
  
 
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.