uva 839

题目大意:
用树模拟天平。判断是否平衡。

思路:
输入的时候要是第一个数字或第三个数字为0的话就表示说他们还有左子树或右子树,如果不为0就是NULL,就利用这种方法建树,然后判断他们是否平衡t->Dl *t->Wl是否等于 t->Dr *t->Wr,不平衡就可以置标记为false,如果等于零的话就递归。

#include <iostream>
using namespace std;

struct Node
{
    int Wl;
    int Dl;
    int Wr;
    int Dr;
    Node *left;
    Node *right;
};
bool ok;
Node * build()  //递归建树
{
    Node *root = new Node();
    scanf("%d%d%d%d", &root->Wl, &root->Dl,&root->Wr,&root->Dr);
    if (root->Wl == 0)
        root->left = build();
    else
        root->left = NULL;
    if (root->Wr == 0)
        root->right = build();
    else
        root->right = NULL;
    return root;
}
/*void rmTree(Node *&root) { if (root == NULL) { return; } else { rmTree(root->left); rmTree(root->right); delete root; root = NULL; } }*/
int Judge(Node * t)
{
    if (ok == false)
        return 0;
    if (t->Wl == 0)
        t->Wl = Judge(t->left);
    if (t->Wr == 0)
        t->Wr = Judge(t->right);
    if (t->Dl *t->Wl != t->Dr *t->Wr)
        ok = false;
    //return (t->Dl *t->Wl + t->Dr *t->Wr); 
    return  (t->Wl + t->Wr);
}
int main()
{
    int n;
    cin >> n;

    while (n--)
    {   
        ok = true;
        Node * root = new Node;
        root = build(); 
        Judge(root);
        if (ok)
            printf("YES\n");
        else
            printf("NO\n");
        //rmTree(root);
        if (n) printf("\n");
    }
    return 0;
}

你可能感兴趣的:(uva 839)