HDU 5444 Elven Postman(二叉树)

题目链接

题目大意

  给一个二叉树,第一个点是根,然后优先访问右儿子,然后是左儿子,右儿子的结点编号比父节点小,左儿子的结点编号比父节点大。

解题思路

  从根开始搜索,如果插入的结点比当前结点小,而且右二儿子存在,就访问右儿子,负责插入的点就是右儿子,左儿子也一样。

代码

const int maxn = 1e3+10;
const int maxm = 1e5+10;
struct NODE {
    int l, r, p;
} node[maxn];
int n; string s[maxn];
void build(int u, int x) {
    if (x<u) {
        if (node[u].r) build(node[u].r, x);
        else node[u].r = x;
    }
    else if (x>u) {
        if (node[u].l) build(node[u].l, x);
        else node[u].l = x;
    }
}
void dfs(int u, int p, int state) {
    if (!u) return;
    if (state==1) s[u] = s[p]+'W';
    else if (state==2) s[u] = s[p]+'E';
    dfs(node[u].l, u, 1);
    dfs(node[u].r, u, 2);
}
int main() {
    IOS; int t; cin >> t;
    while(t--) {
        cin >> n;
        clr(node, 0);
        int root; cin >> root;
        for (int i = 1, num; i<n; ++i) {
            cin >> num; build(root, num);
        }
        s[root] = "";
        dfs(root, 0, 0);
        int m; cin >> m;
        for (int i = 1, num; i<=m; ++i) {
            cin >> num;
            cout << s[num] << endl;
        }
        for (int i = 0; i<=n; ++i) s[i].clear();
    }
    return 0;
}
posted @ 2020-09-21 15:42  shuitiangong  阅读(89)  评论(0编辑  收藏  举报