mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-13 16:19:46 +08:00
Represent null with INT_MAX in C, C++.
This commit is contained in:
@@ -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);
|
||||
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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++;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user