其他分享
首页 > 其他分享> > 判断红黑树

判断红黑树

作者:互联网

https://www.acwing.com/problem/content/1630/

思路:
思路不难,按照题目意思判断即可,但是这个dfs有些难写,值得学习,特记录此题。

#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

const int N = 40;

int pre[N], in[N];
unordered_map<int, int> pos;
bool ans;

int build(int il, int ir, int pl, int pr, int& sum)
{
    int root = pre[pl];
    int k = pos[abs(root)];

    if (k < il || k > ir)
    {
        ans = false;
        return 0;
    }

    int left = 0, right = 0, ls = 0, rs = 0;
    if (il < k) left = build(il, k - 1, pl + 1, pl + 1 + k - 1 - il, ls);
    if (k < ir) right = build(k + 1, ir, pl + 1 + k - 1 - il + 1, pr, rs);

    if (ls != rs) ans = false;
    sum = ls;
    if (root < 0)
    {
        if (left < 0 || right < 0) ans = false;
    }
    else sum ++ ;

    return root;
}

int main()
{
    int T;
    cin >> T;
    while (T -- )
    {
        int n;
        cin >> n;
        for (int i = 0; i < n; i ++ )
        {
            cin >> pre[i];
            in[i] = abs(pre[i]);
        }

        sort(in, in + n);

        pos.clear();
        for (int i = 0; i < n; i ++ ) pos[in[i]] = i;

        ans = true;
        int sum;
        int root = build(0, n - 1, 0, n - 1, sum);

        if (root < 0) ans = false;
        if (ans) puts("Yes");
        else puts("No");
    }

    return 0;
}

标签:判断,int,sum,红黑树,il,ans,root,pl
来源: https://www.cnblogs.com/xjtfate/p/16603241.html