Time complexity of recursive algorithms: recursive tree

Source: Internet
Author: User

RecursionAlgorithmThe time complexity calculation equation is a recursive equation:

Before introducing a recursive tree, consider the following example:

T (n) = 2 T (n/2) + N2

Iterations can be:

T (n) = n2 + 2 (2 T (N/4) + (n/2) 2)

You can continue the iteration and expand it completely:

T (n) = n2 + 2 (n/2) 2 + 2 (n/22) 2 + 2 (n/23) 2 + 2 (n/24) 2 +... + 2 (n/2I) 2 + 2 T (N/2I + 1 )))...)))) ...... (1)

When N/2I + 1 = 1, the iteration ends.

 

Expand the parentheses (1) to obtain the following information:

T (n) = n2 + 2 (n/2) 2 + 22 (n/22) 2 +... + 2I (N/2I) 2 + 2I + 1 T (N/2I + 1)

This happens to be a tree structure, which leads to the recursive tree method.

 

(A) (B) (c) (d) in the figure are steps 1, 2, 3, and N generated by the recursive tree. The current Free item N2 is left in each node, and two recursive items T (n/2) + T (n/2) the two subnodes are shared with each other.

Sum of all nodes in the figure:

[1 + 1/2 + (1/2) 2 + (1/2) 3 +... + (1/2) I] n2 = 2n2

The time complexity is O (n2)

The rule of the recursive tree is as follows:

(1) the nodes in each layer are the values of F (n) in T (n) = kt (N/m) + f (n) under the current N/m;

(2) the number of branches of each node is K;

(3) mark the sum of all nodes in the current layer on the right of each layer.

 

Another example:

T (n) = T (N/3) + T (2n/3) + n

Shows the recursive tree:

The value of each layer is N. The longest path from the root node to the leaf node is:

Because the last recursive stop is in (2/3) kN = 1. Then

Therefore

That is, T (n) = O (nlogn)

 

SummaryTo solve the complexity of recursive algorithms:

F (n) = AF (N/B) + d (N)

1. When D (n) is a constant:

2. When D (n) = cn:

3. When D (n) is in other cases, recursive trees can be used for analysis.

In the second case, If the method of division and control is used to improve the original algorithm, the focus is to reduce the value by using a new calculation method.

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.