zoukankan      html  css  js  c++  java
  • 二叉树的递归遍历——天平(递归输入)

    一、题目,

    输入一个树状数组,根据力矩相等原则判断是否平衡。采用递归方式输入(先序):每个天平的格式为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
    ");
    28         else    printf("NO
    ");
    29 
    30         if (T)    printf("
    ");
    31     }
    32     return 0;
    33 }
  • 相关阅读:
    诊断Oracle 服从成绩
    联机热备份失踪败后,怎样翻开数据库?
    Oracle 8.0.4 for Windows NT的装配
    Oracle常用数据字典
    怎样快速查出Oracle数据库中的锁等待
    Oracle不凡包
    Developer/2000 R2.1 中文版 在 Windows NT 上的安置
    Oracle中巧用FORMS_DDL
    Oracle 基本常识
    autorun的执行的命令行
  • 原文地址:https://www.cnblogs.com/lfri/p/9504954.html
Copyright © 2011-2022 走看看