二叉树的递归遍历——天平(递归输入)

一、题目,

输入一个树状数组,根据力矩相等原则判断是否平衡。采用递归方式输入(先序):每个天平的格式为Wl, Dl ,Wr ,Dr,当Wl或Wr为0时,

表示该“砝码”实际是一个子天平,接下来会描述这个子天平。 当Wl = Wr  = 0时,会先描述左子天平,再描述右子天平。

二、解题思路

题目的输入就是采用递归的方式给的,自然要编个递归的方式输入。可以递归处理,到达根节点时,判断是否平衡,并将总重量传递给父天平。

由于引用传值,代码非常精简。紫书说这题极为重要,要确保完全理解。

三、代码实现

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cstdbool>
 6 using namespace std;
 7 
 8 bool slove(int& W)
 9 {
10     int W1, D1, W2, D2;
11     bool b1 = true,b2 = true;
12     scanf("%d%d%d%d", &W1, &D1, &W2, &D2);
13     if (!W1)    b1 = slove(W1);
14     if (!W2)    b2 = slove(W2);
15 
16     //到达叶子节点,进行判断,并更新重量
17     W = W1 + W2;
18     return b1 && b2 && W1 * D1 == W2 * D2;
19 }
20 
21 int main()
22 {
23     int T, W;
24     scanf("%d", &T);
25     while (T--)
26     {
27         if (slove(W)) printf("YES\n");
28         else    printf("NO\n");
29 
30         if (T)    printf("\n");
31     }
32     return 0;
33 }

猜你喜欢

转载自www.cnblogs.com/lfri/p/9504954.html