[Leetcode] Unique Binary Search Trees II

Source: Internet
Author: User

Title: (DP)

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

Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

Exercises

Reference Http://www.tuicool.com/articles/JJVbA3U

  PublicArraylist<treenode> Generatetrees (intN) {//Start Typing your Java solution below//Do not write main () function        returnGeneratetrees (1, N); }         PublicArraylist<treenode> Generatetrees (intAintb) {ArrayList<TreeNode> res =NewArraylist<treenode>(); if(a>b) {Res.add (NULL); }Else if(a==C) {Res.add (NewTreeNode (a)); }Else if(a<b) {             for(inti=a;i<=b;i++) {ArrayList<TreeNode> Temp1 = generatetrees (a,i-1); ArrayList<TreeNode> Temp2 = generatetrees (i+1, B);  for(TreeNode n:temp1) { for(TreeNode m:temp2) {TreeNode temp=NewTreeNode (i); Temp.left=N; Temp.right=m;                    Res.add (temp); }                }            }        }         returnRes; }

This problem is more difficult than 1 is not the number of returns, but the return of all results. Referring to code Ganker (http:1,2,3,4,.. N, BST builds on the following principles are unique: a tree with I as the root node, the left subtree is composed of [1, I1], and its right subtree is [i+1, n] constitute.    The code is as follows:    

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