"Leetcode" Unique Binary Search Trees II

Source: Internet
Author: User

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

Since 1~n is the ascending sequence, the tree that is built naturally is BST.

Recursive thinking, select the root node, and then separate the left and right sub-sequences.

Since the results of the left and right sub-sequences may be more than one, consideration should be given to all collocation situations.

/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: Vector<treenode *> Generatetrees (intN) {vector<treenode *>Res; if(n = =0) {res.push_back (NULL); returnRes; }        Else         {            returnHelper (1, N); }} vector<TreeNode*> Helper (intBeginintend) {Vector<TreeNode*>Res; if(Begin >end)            {Res.push_back (NULL); returnRes; }        Else if(Begin = =end) {TreeNode* Root =NewTreeNode (begin);            Res.push_back (root); returnRes; }        Else        {             for(inti = begin; I <= end; i + +)            {                //TagVector<treenode*> left = Helper (begin, I-1); Vector<TreeNode*> right = Helper (i+1, end);  for(intL =0; L < Left.size (); L + +)                {//All BST in left                     for(intR =0; R < Right.size (); R + +)                    {//All BST on right//New root here! not the tag position.treenode* root =NewTreeNode (i); Root->left =Left[l]; Root->right =Right[r];                    Res.push_back (root); }                }                            }            returnRes; }    }};

"Leetcode" Unique Binary Search Trees II

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.