Uva--112 / Poj--1145(二叉树,建树,遍历)

2014-06-19 19:51:42

题意&思路:以Lisp语句表达式的形式给出二叉树,再问从根到任意节点路径上点值总和是否等于某个值。有了Uva548的经历,这题敲起来顺手多了,虽然还是花了不少时间 (QAQ!)

有趣的是对于 0 () 这种情况,(即空树,要求的值为0),Uva和Poj给出了两种答案,Uva:no, Poj:yes / no 都过

显然Uva的数据更加严谨,但Poj把这组0 ()这组数据删掉应该是为了取消歧义。

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 
 5 struct node{
 6     int val;
 7     node *left,*right;
 8     node(){
 9         left = right = NULL;
10         val = 0;
11     }
12 };
13 int n1,n2,tag,tar;
14 
15 node * Build_tree(){
16     char t;
17     node * next = new node;
18     int flag = 1,non = 0,num = 0;
19     t = getchar();
20     if(t == '\n' || t == ' ' || t == '('){
21         while(t == '\n' || t == ' ')    t = getchar();
22         if(t == '(')    n1++;
23         t = getchar();
24     }
25     if(t == ')'){
26         n2++;
27         flag = 0; //表示空
28         return NULL;
29     }
30     else{
31         if(t == '-'){
32             non = 1;
33             t = getchar();
34         }
35         while(t >= '0' && t <= '9'){
36             num = num * 10 + (int)(t - '0');
37             t = getchar();
38         }
39     }
40     if(non)    num = -num;
41     if(t == '(')    n1++;
42     else if(t == ')')   n2++;
43     if(n1 == n2)
44         return next;
45 
46     next->val = num;
47     next->left = Build_tree();
48     next->right = Build_tree();
49 
50     if(flag){
51         while((t = getchar()) != ')');
52         n2++;
53     }
54     return next;
55 }
56 void Dfs(node *tem,int sum){
57     sum += tem->val;
58     if(tem->left == NULL && tem->right == NULL){
59         if(sum == tar)  tag = 1;
60         return;
61     }
62     if(tem->left != NULL)
63         Dfs(tem->left,sum);
64     if(tem->right != NULL)
65         Dfs(tem->right,sum);
66 }
67 void Del(node *tem){
68     if(tem == NULL)
69         return;
70     if(tem->left != NULL) Del(tem->left);
71     if(tem->right != NULL) Del(tem->right);
72     delete tem;
73 }
74 int main(){
75     node *root = new node;
76     char c;
77     while(scanf("%d",&tar) == 1){
78         tag = 0;
79         n1 = n2 = 0;
80         root = Build_tree();
81         if(root != NULL)
82             Dfs(root,0);
83         if(tag) printf("yes\n");
84         else printf("no\n");
85         Del(root);
86         root = NULL;
87     }
88     return 0;
89 }

 

posted @ 2014-06-19 19:56  Naturain  阅读(158)  评论(0编辑  收藏  举报