二叉树的表达

2019-08-03

19:52:58

#include <bits/stdc++.h>
using namespace std;
#define MAX 100005
#define NIL -1

int H[MAX];
int D[100005];
struct Node{
    int parent,left,right;
}t[MAX];

void setDepth(int u, int d)
{
    if(u == NIL) return ;
    D[u] = d;
    setDepth(t[u].left, d + 1);
    setDepth(t[u].right, d + 1);
}

int setHeight(int u)
{
    int h1 = 0,h2 = 0;
    if(t[u].left != NIL)
    {
        h1 = setHeight(t[u].left) + 1;
    }
    if(t[u].right != NIL)
    {
        h2 = setHeight(t[u].right) + 1;
    }
    H[u] = max(h1 , h2);
    return H[u];
}

int getSibling(int u)
{
    if(t[u].parent == NIL) return NIL;
    if(t[t[u].parent].left != u && t[t[u].parent].left != NIL)
    {
        return t[t[u].parent].left;
    }
    if(t[t[u].parent].right != u && t[t[u].parent].right != NIL)
    {
        return t[t[u].parent].right;
    }
    return NIL;
}
void print(int u)
{
    printf("node %d: ", u);
    printf("parent = %d, ",  t[u].parent);
    printf("sibling = %d, ", getSibling(u));
    int deg = 0;
    if(t[u].left != NIL) deg++;
    if(t[u].left != NIL) deg++;
    printf("degree = %d, ", deg);
    printf("depth = %d, ", D[u]);
    printf("height = %d, ", H[u]);
    
    if(t[u].parent == NIL)
    {
        printf("root\n");
    }
    else if(t[u].left == NIL && t[u].right == NIL)
    {
        printf("leaf\n");
    } 
    else
    {
         printf("internal node\n");
    }
}
int main()
{
    int n;
    cin >> n;
    int root = 0;
    
    for(int i = 0; i < n; i++) t[i].parent = NIL;
    
    for(int i = 0 ; i < n ;i++)
    {
        int v;
        int l, r;
        cin >> v >> l >> r;
        t[i].left = l;
        t[i].right = r;
        if(l != NIL) t[l].parent = v;
        if(r != NIL) t[r].parent = v;
    }
    
    for(int i = 0; i < n; i++)
    {
        if(t[i].parent == NIL) root = i;
    }
    setDepth(root, 0);
    setHeight(root);
    
    for(int i = 0; i < n; i++)
    {
        print(i);
    }
    cout << getSibling(3) << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Artimis-fightting/p/11296051.html