Node Class
Lesson 3 of 16 in Coddy's AVL Tree - Data Structures Series #10 course.
Every node in the tree stores four things: its value, pointers to a left and right child, and its own height. A brand new node is a leaf, so its height starts at 1 and it has no children yet.
Tracking height directly on the node (instead of recomputing it by walking the tree every time) is what lets every later operation check balance in constant time.
Challenge
BeginnerWrite a class Node with a constructor that takes a value and stores it, sets left and right to null, and sets height to 1.
Try it yourself
#include <stdio.h>
#include "node.h"
int main(void) {
char line[256];
while (fgets(line, sizeof(line), stdin) != NULL) {
int v;
if (sscanf(line, "%d", &v) != 1) {
continue;
}
Node* n = Node_create(v);
if (n->left == NULL && n->right == NULL) {
printf("%d %d null null\n", n->value, n->height);
} else if (n->left == NULL) {
printf("%d %d null %d\n", n->value, n->height, n->right->value);
} else if (n->right == NULL) {
printf("%d %d %d null\n", n->value, n->height, n->left->value);
} else {
printf("%d %d %d %d\n", n->value, n->height, n->left->value, n->right->value);
}
}
return 0;
}
All lessons in AVL Tree - Data Structures Series #10
2AVL Tree Project
Node ClassAVLTree Class