Poj 2499 calculates the path length from a binary tree node to the root node. Recursive Binary Tree

Source: Internet
Author: User

This subject requires the path length from a binary tree node to the root node. The basic idea is to compare a and B. If a is large, the current node is left child, a-B is the left Number of the parent node. the right number of the parent node is equal to the current right number. If B is large, the current node is the right child. Similarly, you can find the parent node, the traversal ends until the parent node is (1, 1.

When the original recursive algorithm times out, consider the special circumstances of a = 1 or B = 1, and use the multiples of A and B to speed up the traversal.

Source code

Problem:2499   User:
Yangliuacmer
Memory:244 K   Time:0 ms
Language:C ++   Result:Accepted
# Include <iostream> using namespace STD; void travelcount (Int & L, Int & R, int A, int B) {/* Original recursive algorithm, not optimized, tleif (A = 1 & B = 1) {return;} If (A> B) {// (A, B) is the left child travelcount (++ l, r, A-B, B);} else travelcount (L, ++ R, a, B-); * // change the recursive form to the loop form (non-recursive form) while (! = 1 | B! = 1) {if (a = 1) {// if only a is 1, only the right path is taken, which must be the right child, directly calculate the difference and convert it into steps R + = B-A; break;} If (B = 1) {L + = A-B; break ;} // use the multiples of A and B to take multiple steps each time to speed up the traversal. If (A> B) {L + = A/B; a-= B * (a/B);} else {R + = B/a; B-= A * (B/A) ;}} int main () {int N, A, B, l, R, I = 1; CIN> N; while (n --) {CIN> A> B; L = r = 0; travelcount (L, R, a, B); cout <"Scenario #" <(I ++) <":" <Endl; cout <L <"" <r <Endl;} return 0 ;}

Reference http://www.cnblogs.com/allensun/archive/2010/11/08/1872028.html

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.