LeetCode-96. Unique Binary Search Trees

Source: Internet
Author: User

Description:

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

Problem: Give an integer n, calculate the type of two-fork search tree with the number of nodes N.

The simplest idea of this topic should be to recursively construct a two-fork lookup tree so that each node becomes the root node. This is a time of high complexity. There is also a dynamic programming method. The description is as follows:

If the whole tree has n nodes, the root node is 1 nodes, and two subtrees divide the remaining n-1 nodes.

Suppose we already know that the two-fork tree with the number of nodes x is of a dp[x] different form.

Then the number of nodes of the left node of a binary tree is K , and its morphology number is dp[k] * dp[n - 1 - k] .

For an n -node Two-fork tree, the scheme of two sub-tree allocation nodes is n-1 :

(0, n-1), (1, n-2), ..., (n-1, 0)

So we can get a two-fork tree for n nodes with the form:

Sigma(dp[i] * dp[n-1-i]) | i = 0 .. n-1

And it can be found that the dp array has a recursive relationship, we can use recursive or memory search to achieve.

The boundary condition is dp[0] = 1 .

The above analysis sources here

Java Code:

 Public classSolution {int[] RC;  Public intNumtrees (intN) {RC=New int[N+1]; Arrays.fill (RC,0); returnDP (n); }         Public intdpintnodes) {        if(Nodes <= 1)            return1; if(rc[nodes]! = 0)            returnRc[nodes]; intNumtrees = 0;  for(inti=0; i<nodes; i++) {numtrees+ = DP (i) * DP (nodes-i-1); } Rc[nodes]=numtrees; returnnumtrees; }}

LeetCode-96. 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.