Unique Binary Search Trees II

Source: Internet
Author: User

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

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 of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * p Ublic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/*** @paramn N:an integer *@return: A List of root*/     PublicList<treenode> Generatetrees (intN) {//Write your code here        returnGenerate (1, N); }         PublicList<treenode> Generate (intLeftintRight ) {List<TreeNode> res=NewArraylist<treenode>(); if(left>Right ) {Res.add (NULL); returnRes; }                 for(inti=left;i<=right;i++) {List<TreeNode> lefts= Generate (left,i-1); List<TreeNode> rights= Generate (i+1, right);  for(intJ=0;j<lefts.size (); j + +)            {                 for(intK=0;k<rights.size (); k++) {TreeNode root=NewTreeNode (i); Root.left=Lefts.get (j); Root.right=Rights.get (k);                Res.add (root); }                            }        }                returnRes; }}

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.