[C + +] leetcode:53 Unique Binary Search Trees

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

Background knowledge:

two fork Find Tree ( English:binarysearch tree), also known as the binary searching trees, ordered binary trees ( English:ordered binarytree), Sort binary trees ( English:sorted binarytree) refers to an empty tree or a two-fork tree with the following properties:

    1. If the left subtree of any node is not empty, the value of all nodes on the left subtree is less than or equal to the value of its root node;
    2. The right subtree of any node is not empty, then the value of all nodes on the right subtree is greater than the value of its root node;
    3. The left and right subtrees of any node are also two-fork lookup trees, respectively.
    4. No nodes with key values equal ( English:No Duplicate Nodes).

Anwser 1: Recursive method

Ideas: how many two-fork search trees can be formed by digital 1~n.

By traversing the selection of a point I as the root of the tree from the 1~n, the combination of the left and right subtrees numtrees the numtrees of the current root.

According to the definition of binary search tree, the number of nodes of left subtree is (i-1) and the right subtree is (n-i).

AC Code:

Class Solution {public:    int numtrees (int n) {        //digital 1~n can constitute how many kinds of two-fork find tree        //recursive method to traverse from 1~n to select a point I as the root of the tree, Then the combination of numtrees (left) and right subtree of the Zuo subtree is the product of the combination of the numtrees, which is the number of combinations of the current root.        //According to the definition of binary search tree, the number of left subtree nodes is (i-1), the right subtree is (n-i)        if (n = = 0 | | n = = 1)        {            return 1;        }        else        {            int ret = 0;            for (int i = 1; I <= n; i++)                      //i represents root            {                ret + = (numtrees (i-1)) * (Numtrees (n-i));    Left * Right            }            return ret;}}    ;

Anwser 2: Non-recursive method

Ideas:

To analyze the problem, it is assumed that f (n) indicates the number of BST ' s trees when the 1~n nodes are given

F (n) = f (0) * F (n-1)//make 1 as root, 2~n right subtree

+ F (1) * F (n-2)//Make 2 as root, 1 as left subtree, 3~n right sub-tree

+ ........

+ F (n-1) * F (0)//make n root, 1~n-1 as left subtree.

The recursive form conforms to the Catalain number model.

Number of Catalain:


Maintenance Result[i] represents the number of two-fork lookup trees that contain I nodes . Then, according to the recursive formula analyzed above, we find F (1), F (2),...... f (n) in turn.

Attention:

1. Initialize the first two items of the container before you can begin the iteration.

Result.push_back (1);
Result.push_back (1);

2. Calculate the number of binary lookup trees with I nodes, J indicates that 1~i takes any node as the root. So the method of calculation is the same as recursion, Zuozi (J-1) * Right subtree (i-j)

3. Implementing Recursive formulas

Sum + = (result[j-1] * result[i-j]);

4. Maintain a container of result, the number of the end of the container is the desired f (N). Therefore, each calculation must first reset 0, the iteration to obtain the results and then push into the container.

for (int i = 2; I <= n; i++)
{
int sum = 0;
Calculates the number of binary lookup trees that contain I nodes, and J indicates that 1~i takes any node as the root.
for (int j = 1; J <= I; j + +)
{
Sum + = (result[j-1] * result[i-j]); Left Tree * Right tree implementation recursive formula
}
result.push_back (sum);
}

complexity: The number of two forks to find a tree for each of the I nodes needs an i-step loop, which requires n times in total. Total time complexity O (1+2+3+....+n) = O (n^2)

Space requires a container to maintain, and requires all the information of the first I, so is O (N)

AC Code:

Class Solution {public:    int numtrees (int n) {        vector<int> result;        Result.push_back (1);        Result.push_back (1);                The total number of binary look-up trees is a feasible result of all nodes as root for        (int i = 2; I <= n; i++)        {            int sum = 0;            Calculates the number of binary lookup trees that contain I nodes, and J indicates that 1~i takes any node as the root. For            (int j = 1; J <= I; j + +)            {                sum + = (result[j-1] * result[i-j]);   Left tree * Right tree  implements recursive formula            }                        result.push_back (sum);        }                return Result.back ();    }};


[C + +] leetcode:53 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.