1 solutions

  • 0
    @ 2026-11-18 18:59:41

    C++ :

    #include <bits/stdc++.h>
    #define N 10005
    using namespace std;
    
    struct Node{
        int l,r,h;
    } tre[N];
    
    bool dfs(int u){
        if (tre[u].l!=0) {
            if (!dfs(tre[u].l)){
                return false;
            }
        }
        if (tre[u].r!=0) {
            if (!dfs(tre[u].r)){
                return false;
            }
        }
        
        if (abs(tre[tre[u].l].h - tre[tre[u].r].h) > 1) return false;
        tre[u].h = max(tre[tre[u].l].h,tre[tre[u].r].h) + 1;
        return true;
    }
    
    int main(){
        int n;
        cin >> n;
        for (int i = 1;i<=n;i++){
            cin >> tre[i].l >> tre[i].r;
        }
        
        if (dfs(1)) cout << "Yes";
        else cout << "No";
        return 0;
    }
    
    • 1

    Information

    ID
    352
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    10
    Tags
    # Submissions
    4
    Accepted
    3
    Uploaded By