Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /******************************************************************************
- Online C Compiler.
- Code, Compile, Run and Debug C program online.
- Write your code in this editor and press "Run" button to compile and execute it.
- *******************************************************************************/
- #include <stdio.h>
- #include <stdlib.h>
- struct _node {
- int id;
- int p;
- int sibling;
- int degree;
- int depth;
- int height;
- int type;
- struct _node *left;
- struct _node *right;
- };
- typedef struct _node node;
- int height(node*);
- int max(int, int);
- int main()
- {
- int n, i, d, PP, id, l, r;
- scanf("%d", &n);
- node *T = (node*)malloc(n*sizeof(node));
- /* initialize parents & sibling */
- for (i=0; i<n; i++) {
- T[i].p = -1;
- T[i].sibling = -1;
- }
- /* input node info */
- for (i=0; i<n; i++) {
- scanf("%d", &id);
- scanf("%d%d", &l, &r);
- T[id].id = id;
- T[l].p = T[r].p = id;
- T[l].sibling = r;
- T[r].sibling = l;
- if (l!=-1) {
- T[id].left = &(T[l]);
- T[id].right = &(T[r]);
- T[id].degree = 2;
- }
- else {
- T[id].left = NULL;
- T[id].right = NULL;
- T[id].degree = 0;
- }
- }
- /* judge type */
- for (i=0; i<n; i++) {
- if (T[i].p == -1) T[i].type = 0;
- else if (T[i].degree != 0) T[i].type = 1;
- else T[i].type = 2;
- }
- /* calc depth */
- for (i=0; i<n; i++) {
- d = 0;
- PP = i;
- while(1) {
- if (T[PP].p == -1) {
- T[i].depth = d;
- break;
- }
- else {
- PP = T[PP].p;
- d++;
- }
- }
- }
- /* calc height */
- for (i=0; i<n; i++) {
- T[i].height = height(&T[i]) - 1;
- }
- /* print */
- for (i=0; i<n; i++) {
- printf("node %d: ", i);
- printf("parent = %d, ", T[i].p);
- printf("sibling = %d, ", T[i].sibling);
- printf("degree = %d, ", T[i].degree);
- printf("depth = %d, ", T[i].depth);
- printf("height = %d, ", T[i].height);
- if (T[i].type == 0) printf("root");
- else if (T[i].type == 1) printf("internal node");
- else printf("leaf");
- printf("\n");
- }
- free(T);
- return 0;
- }
- int height(node* root) {
- if (root == NULL) return 0;
- return 1 + max(height(root->left), height(root->right));
- }
- int max(int a, int b) {
- if (a > b) return a;
- return b;
- }
Advertisement
Add Comment
Please, Sign In to add comment