LeetCode:第177场周赛 1361

本文介绍了一种验证二叉树结构有效性的算法,通过遍历节点确保每个子节点都被正确处理,并最终检查所有节点是否已被访问。此外,还提供了一个计算两个日期之间天数差异的方法,利用C++标准库进行日期转换和时间差计算。
class Solution {
public:
    bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
        deque<int> q;
        q.push_back(0);
        
        while(!q.empty()) {
            int index  = q.front();
            q.pop_front();
            if(leftChild[index] > -1) {
                q.push_back(leftChild[index]);
                leftChild[index] = -1;
            }
            if(rightChild[index] > -1) {
                q.push_back(rightChild[index]);
                rightChild[index] = -1;
            }
        }
        
        for(int i = 0; i < n; i++) {
            if(leftChild[i]!=-1 || rightChild[i]!=-1) {
                return false;
            }
        }
        return true;
    }
};
class Solution {
public:
    bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
        deque<int> q;
        q.push_back(0);
        
        for(int i = 0; i < n; i++) {
            int index  = q.front();
            q.pop_front();
            if(leftChild[index] > -1) {
                q.push_back(leftChild[index]);
            }
            if(rightChild[index] > -1) {
                q.push_back(rightChild[index]);
            }
            if(q.empty()) {
                for(int j = i; j < n; j++) {
                    if(leftChild[j]!=-1 || rightChild[j]!=-1) {
                        return false;
                    }
                }
            }
        }
        return q.empty();
    }
};
class Solution {
public:
    int daysBetweenDates(string date1, string date2) {
        vector<int> time1 = str2int(date1);
        vector<int> time2 = str2int(date2);
        
        struct tm t1 = {0};
        struct tm t2 = {0};
        double seconds;
        
        t1.tm_year = time1[0]-1900; t1.tm_mon = time1[1]-1; t1.tm_mday = time1[2];
        t2.tm_year = time2[0]-1900; t2.tm_mon = time2[1]-1; t2.tm_mday = time2[2];
        seconds = abs(difftime(mktime(&t1) , mktime(&t2)));
        
        return seconds/86400;
    }
    
    vector<int> str2int(string s) {
        vector<int> ret;
        int year = s[0] * 1000 + s[1] * 100 + s[2] * 10 + s[3];
        int mon = s[5] * 10 + s[6];
        int date = s[8] * 10 + s[9];
        ret.push_back(year);
        ret.push_back(mon);
        ret.push_back(date);
        return ret;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值