Represent null with INT_MAX in C, C++.

This commit is contained in:
krahets
2023-04-18 14:31:23 +08:00
parent ed8fa6aea3
commit 6723cdbc7e
11 changed files with 35 additions and 26 deletions

View File

@@ -17,7 +17,7 @@ void testListNode() {
}
void testTreeNode() {
int nums[] = {1, 2, 3, NIL, 5, 6, NIL};
int nums[] = {1, 2, 3, INT_MAX, 5, 6, INT_MAX};
int size = sizeof(nums) / sizeof(int);
TreeNode *root = arrToTree(nums, size);

View File

@@ -23,13 +23,13 @@ static void printArray(int arr[], int size) {
printf("[");
if (arr != NULL && size != 0) {
for (int i = 0; i < size - 1; i++) {
if (arr[i] != NIL) {
if (arr[i] != INT_MAX) {
printf("%d, ", arr[i]);
} else {
printf("NULL, ");
}
}
if (arr[size - 1] != NIL) {
if (arr[size - 1] != INT_MAX) {
printf("%d]\n", arr[size - 1]);
} else {
printf("NULL]\n");

View File

@@ -11,7 +11,8 @@
extern "C" {
#endif
#define NIL ('#')
#include <limits.h>
#define MAX_NODE_SIZE 5000
struct TreeNode {
@@ -59,14 +60,15 @@ TreeNode *arrToTree(const int *arr, size_t size) {
node = queue[front++];
index++;
if (index < size) {
if (arr[index] != NIL) {
// represent null with INT_MAX
if (arr[index] != INT_MAX) {
node->left = newTreeNode(arr[index]);
queue[rear++] = node->left;
}
}
index++;
if (index < size) {
if (arr[index] != NIL) {
if (arr[index] != INT_MAX) {
node->right = newTreeNode(arr[index]);
queue[rear++] = node->right;
}
@@ -102,7 +104,7 @@ int *treeToArr(TreeNode *root) {
queue[rear++] = node->left;
queue[rear++] = node->right;
} else {
arr[index] = NIL;
arr[index] = INT_MAX;
}
index++;
}