Unique Binary Search Trees--Leetcode

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

Basic ideas:

The composition of the tree is selected as the root of the node.

All the elements on the left side of the node will make up the left subtree of the root node.

And all elements on the right will make up the right subtree of the node.

The number of different binary trees with this element as the root is the different number of different numbers of Zuozi * right subtree.


The recursive type is:

Dp[i] =∑dp[j] * dp[I-1-j] 0<=j<i


Class Solution {public:    int numtrees (int n) {        vector<int> dp (n+1);        Dp[0] = 1;        DP[1] = 1;        for (int i=2, i<=n; i++) {for            (int j=0; j<i; j + +)                Dp[i] + = dp[j] * dp[i-1-j];        }        return dp[n];}    ;


Unique Binary Search Trees--Leetcode

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.