Created
November 4, 2025 12:36
-
-
Save lakshyaraj2006/596aba8ed3fd5648ac970b2cd61d6383 to your computer and use it in GitHub Desktop.
Find the two nodes in a bst whose sum equals k.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<stdio.h> | |
| #include<stdlib.h> | |
| struct TreeNode { | |
| int key; | |
| struct TreeNode* left; | |
| struct TreeNode* right; | |
| }; | |
| struct TreeNode* createNode(int key) { | |
| struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode)); | |
| newNode->key = key; | |
| newNode->left = NULL; | |
| newNode->right = NULL; | |
| return newNode; | |
| } | |
| struct TreeNode* insert(struct TreeNode* root, int key) { | |
| if (root == NULL) { | |
| root = createNode(key); | |
| } else if (key < root->key) { | |
| root->left = insert(root->left, key); | |
| } else { | |
| root->right = insert(root->right, key); | |
| } | |
| return root; | |
| } | |
| int countNodes(struct TreeNode* root) { | |
| if (root == NULL) return 0; | |
| return 1 + countNodes(root->left) + countNodes(root->right); | |
| } | |
| void convertToArray(struct TreeNode* root, int* arr, int* index) { | |
| if (root == NULL) { | |
| return; | |
| } | |
| convertToArray(root->left, arr, index); | |
| arr[(*index)++] = root->key; | |
| convertToArray(root->right, arr, index); | |
| } | |
| int main() { | |
| struct TreeNode* root = NULL; | |
| root = insert(root, 10); | |
| root = insert(root, 8); | |
| root = insert(root, 7); | |
| root = insert(root, 9); | |
| root = insert(root, 12); | |
| root = insert(root, 13); | |
| root = insert(root, 14); | |
| root = insert(root, 15); | |
| int n = countNodes(root); | |
| int* arr = (int*)malloc(n * sizeof(int)); | |
| int index = 0; | |
| convertToArray(root, arr, &index); | |
| int left = 0, right = n-1; | |
| int k = 28; | |
| int nums[2]; | |
| int found = 0; | |
| while (left <= right) | |
| { | |
| if (arr[left] + arr[right] == k) { | |
| nums[0] = arr[left]; | |
| nums[1] = arr[right]; | |
| found = 1; | |
| break; | |
| } else if (arr[left] + arr[right] < k) { | |
| left++; | |
| } else if (arr[left] + arr[right] > k) { | |
| right--; | |
| } | |
| } | |
| if (!found) { | |
| printf("No pairs found whose sum equals %d\n", k); | |
| } else { | |
| for (int j = 0; j < 2; j++) | |
| { | |
| printf("%d ", nums[j]); | |
| } | |
| } | |
| // Free array from memory | |
| free(arr); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment