Leetcode96_unique Binary Search Trees (1 to n how many different two-fork lookup trees can be formed by these nodes) Java troubleshooting

Source: Internet
Author: User

Topic:

Given N, how many structurally unique BST 's (binary search trees) that store values 1 ... n?

For example,
Given N = 3, there is a total of 5 unique BST ' s.

   1         3     3      2      1    \//      /\           3     2     1      1   3      2    /     /       \                    2     1         2                 3
Solving:

With recursive thinking, when there are only 0 or 1 nodes. There is only one. N nodes have an F (n) Type:

The left side can have n-1 nodes, the right 0 nodes, according to the symmetry can be interchanged around. At this time there are 2*f (n-1) *f (0);

On one side 1, there is a side n-2, this time has 2*f (1) *f (n-2);

One side two, one side N-3, this time has 2*f (2) *f (n-3);

。。。

。。。

Suppose N is an odd number and both sides are N/2. At this time there is f (N/2) *f (N/2), assuming that n is even, one side N/2 side (n/2+1), for 2*f (N/2) *f (n/2+1);


Code:

  public static int numtrees (int n) {     if (n==1| | n==0)     return 1;     int sum=0;     if (n%2==0)     {for     (int k=n-1;k>=n/2;k--)         {         sum+=2*numtrees (k) *numtrees (n-1-k);         }         return sum;          }     else {for     (int k=n-1;k>n/2;k--)         {         sum+=2*numtrees (k) *numtrees (n-1-k);         }         Return Sum+numtrees (N/2) *numtrees (N/2);}            }




Leetcode96_unique Binary Search Trees (1 to n how many different two-fork lookup trees can be formed by these nodes) Java troubleshooting

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.