Time Limit: 1 secs, Memory Limit: 32 MBnode
Your task is very simple: Given a binary tree, every node of which contains one upper case character (‘A’ to ‘Z’); you just need to print all characters of this tree in pre-order.ios
Input may contain several test data sets.數組
For each test data set, first comes one integer n (1 <= n <= 1000) in one line representing the number of nodes in the tree. Then n lines follow, each of them contains information of one tree node. One line consist of four members in order: i (integer, represents the identifier of this node, 1 <= i <= 1000, unique in this test data set), c (char, represents the content of this node described as above, ‘A’ <= c <= ‘Z’), l (integer, represents the identifier of the left child of this node, 0 <= l <= 1000, note that when l is 0 it means that there is no left child of this node), r (integer, represents the identifier of the right child of this node, 0 <= r <= 1000, note that when r is 0 it means that there is no right child of this node). These four members are separated by one space.ide
Input is ended by EOF.this
You can assume that all inputs are valid. All nodes can form only one valid binary tree in every test data set.spa
For every test data set, please traverse the given tree and print the content of each node in pre-order. Characters should be printed in one line without any separating space.orm
3 4 C 1 3 1 A 0 0 3 B 0 0 1 1000 Z 0 0 3 1 Q 0 2 2 W 3 0 3 Q 0 0
CAB Z QWQ
ZSUACM Team Memberblog
#include <iostream> #include <cstring> #include <set> #include <vector> #include <algorithm> using namespace std; typedef struct treeNode { int id; char value; int left; int right; } treeNode; //前序遍歷二叉樹 void pre_search(int number, treeNode *nodes, int id, string &result) { for (int i = 0; i < number; i++) {//對於每一個節點均需搜索節點數組來肯定其在數組中的該節點 if (nodes[i].id == id) { result.push_back(nodes[i].value); if (nodes[i].left != 0) pre_search(number, nodes, nodes[i].left, result);//遍歷作左節點 if (nodes[i].right != 0) pre_search(number, nodes, nodes[i].right, result);//遍歷右節點 } } } int main() { int number; while (cin >> number) { int id, left, right; treeNode *nodes = new treeNode[number]; //memset(nodes, NULL, sizeof(nodes)); char value; for (int i = 0; i < number; i++) { cin >> id >> value >> left >> right; nodes[i].id = id; nodes[i].value = value; nodes[i].left = left; nodes[i].right = right; } set<int> rids; set<int> cids; vector<int> difference; int root_id; //根節點的id //如下操做爲肯定根節點的id,此爲本題的關鍵 //由於題中爲規定根節點爲第幾個節點,因此因爲根節點是不會出如今子節點中的 //因此分別得到所有節點的id和所有子節點去掉id = 0 後的id,而後在子節點 //中沒有的id,即爲根節點id,此處使用了集合set for (int i = 0; i < number; i++) { rids.insert(nodes[i].id); cids.insert(nodes[i].left); cids.insert(nodes[i].right); } cids.erase(cids.begin()); //集合爲自動排序且無重複元素的,此處去除0 for (set<int>::iterator it = rids.begin(); it != rids.end(); it++) { if(cids.count(*it) == 0) root_id = *it; } string result; pre_search(number, nodes, root_id, result); cout << result << endl; delete []nodes; } return 0; }