[TOJ 1224] Data Structure exercise-post-order traversal of Binary Trees, toj1224
Description
Given a binary tree, you must output the depth of the Binary Tree and the sequence obtained by traversing the binary tree in descending order. This example assumes that the number of nodes in a binary tree cannot exceed 1000.
Input
The input data is divided into multiple groups. The first row is the number of n groups of test data. The n rows below represent a binary tree. The node of each binary tree is a positive integer. If the data is 0, the current node is empty. If the data is-1, the input of the binary tree is complete and-1 is not processed. The construction of a binary tree is in hierarchical order (that is, Layer 1 integer in Layer 2, Layer 2, Layer 4, and Layer 2 with 8 ......, if a node does not exist, use 0 instead ).
Output
Output the depth of each binary tree and the sequence obtained by traversing the binary tree in a descending order.
Sample input
2
1-1
1 2 0 3 4-1
Sample output
1 1
3 3 4 2 1
# Include <iostream> # include <cstring> # include <algorithm> using namespace std; int a [1005], k; // k is the total number of Binary Tree Elements int post (int n) // n is a parameter starting from 1, indicating the nth element to be traversed {if (n> k) return 0; if (a [2 * n]! = 0) // avoid excessive memory usage post (2 * n) due to invalid traversal; // first traverse from left if (a [2 * n + 1]! = 0) post (2 * n + 1); // then traverse the if (a [n]) cout from the right <"<a [n];} int deep (int n) {int m; if (n> k | a [n] = 0) return 0; int left = deep (2 * n ); int right = deep (2 * n + 1); m = max (left, right) + 1; return m;} int main () {int t, n; cin> t; while (t --) {k = 0; while (cin> n) {if (n =-1) break; a [++ k] = n ;}cout <deep (1); // recursive post (1) with depth starting from 1 ); // recursive cout <endl; memset (a, 0, sizeof a);} return 0 ;}