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 }

 

转载于:https://www.cnblogs.com/naturepengchen/articles/3804515.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值