Unique Binary Search Trees

Source: Internet
Author: User

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
intNumtrees (intN) {int*result =malloc((n +1)*sizeof(int)); if(n = =0|| n = =1)        return 1; if(n = =2)        return 2; result[0] = result[1] =1; result[2] =2;  for(inti =3; I <= N; i++)    {        intTMP =0; Result[i]=0;  for(intj =1; J <= I/2; J + +) TMP+ = Result[j-1] * Result[i-J]; Result[i]= tmp *2; if(I-(I/2) *2) Result[i]+ = Result[i/2] * Result[i/2]; }    returnresult[n];}
    • Select a value in the sequence as the root node, Saozi the right subtree, and can have the product of the remaining number permutations, respectively
    • Because the left and right sides select the same number, you can separate both sides of the calculation
    • When opening up space, it is necessary to open up n+1, and array of [n] Correspondence

Unique Binary Search Trees

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.