Unique Binary Search Trees II--Leetcode

Source: Internet
Author: User

Iven 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.


Basic idea: Recursion

1. Each element in turn is the root node

2. Recursively, all elements to the left of the element, returning a collection of sets of numbers.

3. All elements to the right of the element, generating a set of numbers.

4. Select a tree from the left and right sets to Saozi the right subtree, together with the root node. Make up a tree.


On Leetcode, the actual execution time is 27ms.


/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *};        */class Solution {Public:vector<treenode *> generatetrees (int n) {vector<treenode *> ans;        Generatetrees (ans, 1, n+1);    return ans; } void Generatetrees (Vector<treenode *> &ans, int start, int stop) {for (int i=start; i<stop;            i++) {Vector<treenode *> lefts;            Generatetrees (lefts, start, i);                for (int j=0; j<lefts.size (); j + +) {Vector<treenode *> rights;                Generatetrees (Rights, i+1, stop);                    for (int k=0; k<rights.size (); k++) {TreeNode *root = new TreeNode (i);                    Root->left = Lefts[j];                    Root->right = Rights[k];                Ans.push_back (root);          }            }        }      if (Ans.empty ()) ans.push_back (0); }};


Unique Binary Search Trees II--Leetcode

Related Article

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.