Data Structure uva-699-The Falling Leaves

Source: Internet
Author: User

Give a binary tree to output the sum of values of all nodes at the same horizontal position in the left-to-right order. Solution: Build a hierarchy using recursion, and calculate the sum of each level in the process of building a hierarchy. Here, I mark the root of the tree as 150. Then, the left child's position is reduced by 1 for the immediate father, And the right child adds 1 for the immediate father. code: [cpp] # include <iostream> # include <cmath> # include <cstdio> # include <cstdlib> # include <string> # include <cstring> # include <algorithm> # include <vector> # include <map> # include <stack> # include <queue> # define eps 1e-6 # define INF (1 <20) # define PI acos (-1.0) using namespace std; int ans [330]; void tree (int cur, int loc) {if (cur =-1) // If a leaf node is encountered, the system returns retur. N; ans [loc] + = cur; // otherwise, add the int left, right; scanf ("% d", & left); tree (left, loc-1); // left child, location for parent location minus 1 scanf ("% d", & right); tree (right, loc + 1); // right child, add 1 return;} int main () {int cur, ca = 0; while (scanf ("% d", & cur) & cur! =-1) {memset (ans, 0, sizeof (ans); tree (cur, 150); // set 150 to the initial position int I; for (I = 1; I <= 300; I ++) // remove the preceding 0 if (ans [I]) break; if (I = 301) continue; printf ("Case % d: \ n % d", ++ ca, ans [I]); for (++ I; I <= 300; I ++) // The output value is not 0 and the value if (ans [I]) printf ("% d", ans [I]); printf ("\ n ");} return 0 ;}

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.