Leetcode_num95_unique BT II

Source: Internet
Author: User

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 
/** * 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) {return generatetrees (1,n);        } vector<treenode *>generatetrees (int s,int e) {vector<treenode *> res; if (s>e) res.push_back (0);//the default element is 0 else if (s==e) res.push_back (New Treeno De (s));//new else if (s<e) {for (int i=s;i<=e;i++) {Vector<treenode *>left=gene Ratetrees (s,i-1),//the left subtrees Vector<treenode *>right=generatetrees (i+1,e),//the right subtree                        s for (int j=0;j<left.size (); j + +) {for (int k=0;k<right.size (); k++) {      TreeNode *proot=new TreeNode (i);//every Tree has a rootNode proot->left=left[j];                  proot->right=right[k];                    Res.push_back (Proot);    }}}} return res; }};


Leetcode_num95_unique BT 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.