PATA1135_红黑树(还是蒙的)

本文分享了一段关于二叉树构建与特定条件判断的代码实现。主要涉及递归构建二叉树的方法,并通过两个判断函数来验证树的特性是否符合特定规则。适合对二叉树操作感兴趣的学习者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个题直接没读懂,看了柳神的代码后自己照葫芦画瓢写了。还是有几个点没有搞懂。等二刷再来看看。

#include <bits/stdc++.h>
using namespace std;
struct tree {
    int v;
    tree *lc, *rc;
};
vector<int> arr;
tree *bulid (tree *root, int v) {
    if (root == NULL) {
        root = new tree();
        root->lc = root->rc = NULL;
        root->v = v;
    }
    else if (abs(v) > abs(root->v))
        root->rc = bulid (root->rc, v);
    else
        root->lc = bulid (root->lc, v);
    return root;
}
bool judge1 (tree *root) {
    if (root == NULL) return true;
    if (root->v < 0) {    //这里自己写的是大于>,下面也是换成大于的,但是测试点3、4过不去
    //这里写成大于,如果根节点是负数,下一层是正数,返回的是true,但是下面判断arr[0] > 0应该不影响的啊
        if (root->lc != NULL && root->lc->v < 0) return false;
        if (root->rc != NULL && root->rc->v < 0) return false;
    }
    return judge1(root->lc) && judge1(root->rc);
}
int getNum (tree *root) {
    if (root == NULL) return 0;
    int l = getNum (root->lc);
    int r = getNum (root->rc);
    return root->v > 0 ? max(l, r) + 1 : max(l, r);
}
bool judge2 (tree *root) {
    if (root == NULL) return true;
    int l = getNum (root->lc);
    int r = getNum (root->rc);
    if (l != r) return false;
    return judge2(root->lc) && judge2(root->rc);
}
int main() {
    int n, k;
    scanf ("%d", &n);
    for (int i = 0; i < n; i++) {
        tree *root = NULL;
        scanf ("%d", &k);
        arr.resize(k);
        for (int j = 0; j < k; j++) {
            scanf ("%d", &arr[j]);
            root = bulid (root, arr[j]);
        }
        if (arr[0] > 0 && judge1(root) == true && judge2(root) == true)
            printf ("Yes\n");
        else 
            printf ("No\n");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值