Skip to content

Instantly share code, notes, and snippets.

@1kohei1
Last active December 4, 2015 23:58
Show Gist options
  • Save 1kohei1/bb68f6357e7cd74306d0 to your computer and use it in GitHub Desktop.
Save 1kohei1/bb68f6357e7cd74306d0 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* createNode(int data);
struct node* insert(struct node* node, int data);
void freeRoot(struct node* node);
void printRoot(struct node* node);
void solve(struct node* node, int k);
int search(struct node* node, int val);
int count;
int main() {
struct node* root = NULL;
int i, n, k;
scanf("%d%d", &n, &k);
int* nums = malloc(sizeof(int) * n);
for (i = 0; i < n; i++) {
scanf("%d", &nums[i]);
root = insert(root, nums[i]);
}
for (i = 0; i < n; i++) {
if (search(root, nums[i] + k)) {
count++;
}
}
printf("%d\n", count);
free(nums);
freeRoot(root);
}
struct node* createNode(int data) {
struct node* temp = malloc(sizeof(struct node));
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
struct node* insert(struct node* node, int data) {
if (node == NULL) {
return createNode(data);
}
if (data > node->data) {
node->right = insert(node->right, data);
} else {
node->left = insert(node->left, data);
}
return node;
}
void freeRoot(struct node* node) {
if (node != NULL) {
freeRoot(node->left);
freeRoot(node->right);
free(node);
}
}
// Print root by in order
void printRoot(struct node* node) {
if (node != NULL) {
printRoot(node->left);
printf("%d ", node->data);
printRoot(node->right);
}
}
int search(struct node* node, int val) {
if (node == NULL) {
return 0;
}
if (node->data == val) {
return 1;
} else if (node->data < val) {
return search(node->right, val);
} else {
return search(node->left, val);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment