Uva--699 (二叉树,遍历)
2014-06-20 23:57:57
题意&思路:非常典型的仅根据先序遍历以及结束节点特点,建立二叉树,然后遍历搜索。
1 #include <cstdio> 2 #include <string> 3 #include <sstream> 4 #include <cstring> 5 #include <iostream> 6 using namespace std; 7 8 struct node{ 9 int val; 10 node *left,*right; 11 node(){ 12 val = 0; 13 left = right = NULL; 14 } 15 }; 16 17 int num,cnt,leaves[2048]; 18 19 node *Build_tree(){ 20 node *next = new node; 21 cin >> num; 22 if(num == -1) 23 return NULL; 24 next->val = num; 25 next->left = Build_tree(); 26 next->right = Build_tree(); 27 28 return next; 29 } 30 31 void Dfs(node *tem,int pos){ 32 leaves[pos] += tem->val; 33 if(tem->left != NULL) 34 Dfs(tem->left,pos - 1); 35 if(tem->right != NULL) 36 Dfs(tem->right,pos + 1); 37 } 38 39 int main(){ 40 node *root = new node; 41 int Case = 0; 42 while(1){ 43 memset(leaves,0,sizeof(leaves)); 44 root = Build_tree(); 45 if(root == NULL) 46 break; 47 //printf("%d\n",cnt); 48 Dfs(root,1024); 49 printf("Case %d:\n",++Case); 50 int head = 1; 51 for(int i = 0; i < 2048; ++i){ 52 if(leaves[i] != 0){ 53 if(head){ 54 printf("%d",leaves[i]); 55 head = 0; 56 } 57 else{ 58 printf(" %d",leaves[i]); 59 } 60 } 61 } 62 printf("\n\n"); 63 } 64 return 0; 65 }