Binary Tree

来源:互联网 发布:中美撞机事件真相 知乎 编辑:程序博客网 时间:2024/05/21 01:29
DescriptionYour 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.InputInput 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.      Input is ended by EOF.      You can assume that all inputs are valid. All nodes can form only one valid binary tree in every test data set.OutputFor 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.Sample InputCopy sample input to clipboard34 C 1 31 A 0 03 B 0 011000 Z 0 031 Q 0 22 W 3 03 Q 0 0Sample OutputCABZQWQ#include <iostream>#include <cstring>using namespace std;struct TreeNode{    int lchild;    int rchild;    char val;};TreeNode TreeArray[1001];void preorder(int rootID){    if(rootID != 0){        cout<<TreeArray[rootID].val;        preorder(TreeArray[rootID].lchild);        preorder(TreeArray[rootID].rchild);    }} int main(){    int n;    TreeNode Input;    int InputID,rootID;    bool NodeExit[1001],IsChild[1001];        while(cin>>n){        memset(NodeExit,false,sizeof(NodeExit));        memset(IsChild,false,sizeof(IsChild));                while(n--){            cin>>InputID>>Input.val>>Input.lchild>>Input.rchild;            TreeArray[InputID] = Input;            NodeExit[InputID] = true;            IsChild[Input.lchild] = true;            IsChild[Input.rchild] = true;        }                for(rootID = 1;rootID < 1001;rootID++){            if(NodeExit[rootID] && !IsChild[rootID]){                break;            }        }                 preorder(rootID);        cout<<endl;            }    return 0;}

0 0