原题链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=780
先建立二叉树,之后遍历。
1 #include<iostream> 2 using namespace std; 3 4 struct Node 5 { 6 int W1, D1, W2, D2; 7 Node *left; 8 Node *right; 9 }; 10 11 bool flag; 12 13 Node* creatTree() 14 { 15 Node* root = new Node; 16 cin >> root->W1 >> root->D1 >> root->W2 >> root->D2; 17 if (root->W1 == 0) root->left = creatTree(); 18 else root->left = NULL; 19 if (root->W2 == 0) root->right = creatTree(); 20 else root->right = NULL; 21 return root; 22 } 23 24 int balance(Node* root) 25 { 26 if (flag == false) return 0; 27 if (root->W1 == 0) root->W1 = balance(root->left); 28 if (root->W2 == 0) root->W2 = balance(root->right); 29 if (root->W1*root->D1 != root->W2*root->D2) flag = false; 30 return(root->W1 + root->W2); 31 } 32 33 void remove_tree(Node* u) 34 { 35 if (u == NULL) return; 36 remove_tree(u->left); 37 remove_tree(u->right); 38 delete u; 39 } 40 41 int main() 42 { 43 int t; 44 cin >> t; 45 while (t--) 46 { 47 Node* root = NULL; 48 flag = true; 49 root=creatTree(); 50 flag = true; 51 balance(root); 52 if (flag == true) cout << "YES" << endl; 53 else cout << "NO" << endl; 54 remove_tree(root); 55 if (t != 0) cout << endl; 56 } 57 }
刘汝佳的书上给出了一个引用传值的简单的方法
1 #include<iostream> 2 using namespace std; 3 4 bool solve(int &W) 5 { 6 int W1, D1, W2, D2; 7 bool b1 = true, b2 = true; 8 cin >> W1 >> D1 >> W2 >> D2; 9 if (!W1) b1 = solve(W1); 10 if (!W2) b2 = solve(W2); 11 W = W1 + W2; 12 return b1&&b2 && (W1*D1 == W2*D2); 13 } 14 15 int main() 16 { 17 int T, W; 18 cin >> T; 19 while (T--) 20 { 21 if (solve(W)) cout << "YES" << endl; 22 else cout << "NO" << endl; 23 if (T) cout << endl; 24 } 25 return 0; 26 }