Uva--839 (二叉树,遍历)

2014-06-23 17:58:28

题意&思路:根据给出的实际天平问题构建二叉树(好吧,只能说偏实际)。思路就是以每个天平的支点构建结构体,参数有wl,dl,wr,dr,左右指针,这样便可以完全描述一个天平了。

(第二个版本摘自小白书第二版,非常精简)

 1 #include <cstdio>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 struct node{
 6     int wl,dl,wr,dr;
 7     node *left,*right;
 8     node(){
 9         wl = dl = wr = dr = 0;
10         left = right = NULL;
11     }
12 };
13 
14 node *Build_tree(){
15     node *next = new node;
16     scanf("%d %d %d %d",&next->wl,&next->dl,&next->wr,&next->dr);
17     if(next->wl == 0){
18         next->left = Build_tree();
19         next->wl = next->left->wl + next->left->wr;
20     }
21     if(next->wr == 0){
22         next->right = Build_tree();
23         next->wr = next->right->wl + next->right->wr;
24     }
25     return next;
26 }
27 
28 int tag;
29 
30 void Dfs(node *tr){
31     if(tr->wl * tr->dl != tr->wr * tr->dr){
32         tag = 0;
33         return;
34     }
35     if(tag && tr->left != NULL)
36         Dfs(tr->left);
37     if(tag && tr->right != NULL)
38         Dfs(tr->right);
39 }
40 
41 int main(){
42     node *root = new node;
43     int Case;
44     scanf("%d",&Case);
45     while(Case--){
46         root = Build_tree();
47         tag = 1;
48         Dfs(root);
49         if(tag) cout << "YES" << endl;
50         else cout << "NO" << endl;
51         if(Case) cout << endl;
52     }
53     return 0;
54 }

 版本二:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 bool Tree_judge(int &w){//传入w,从而得到这个分天平的总重量
 5     int wl,dl,wr,dr;
 6     bool b1 = true,b2 = true;
 7     cin >> wl >> dl >> wr >> dr;
 8     if(!wl) b1 = Tree_judge(wl);
 9     if(!wr) b2 = Tree_judge(wr);
10     w = wl + wr;//sodesi
11     return b1 && b2 && (wl * dl == wr * dr);
12 }    
13 
14 int main(){
15     int Case,w;
16     cin >> Case;
17     while(Case--){
18         if(Tree_judge(w)) cout << "YES" << endl;
19         else cout << "NO" << endl;
20         if(Case) cout << endl;
21     }
22     return 0;
23 }

 

posted @ 2014-06-23 18:00  Naturain  阅读(147)  评论(0)    收藏  举报