> For the complete documentation index, see [llms.txt](https://gl01.gitbook.io/gfg-editorials/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gl01.gitbook.io/gfg-editorials/2023/06-2023-june-4/05-find-the-closest-element-in-bst.md).

# 05. Find the Closest Element in BST

The problem can be found at the following link: [Question Link](https://practice.geeksforgeeks.org/problems/find-the-closest-element-in-bst/1)

## My Approach

To find the closest element to a given key (`K`) in a binary search tree (BST), I have used the following approach:

* Traverse the BST while comparing each node's value with the target key (`K`).
* Keep track of the minimum difference (`md`) found so far between the node's value and the target key, as well as the node value (`md_key`) associated with the minimum difference.
* Recursively check the left and right subtrees based on the target key's value compared to the current node's value.
* Update `md` and `md_key` if a closer value is found.
* Finally, return the absolute difference between `md_key` and `K`.

## Time and Auxiliary Space Complexity

* **Time Complexity**: `O(N)`, where `N` is the number of nodes in the BST. However, on average, for a balanced BST, the time complexity is `O(log N)`.
* **Auxiliary Space Complexity**: `O(1)` since we are not using any extra space that scales with the input.

## Code (C++)

```cpp
class Solution {
public:
    void check(struct Node *node, int k, int &md, int &md_key){
        if (node == NULL)
            return;
     
        if (node->data == k){
            md_key = k;
            return;
        }
     
        if (md > abs(node->data - k)){
            md = abs(node->data - k);
            md_key = node->data;
        }
     
        if (k < node->data)
            check(node->left, k, md, md_key);
        else
            check(node->right, k, md, md_key);
    }
     
    int minDiff(Node *root, int k){
        int md = INT_MAX, md_key = -1;
        check(root, k, md, md_key);
     
        return abs(md_key - k);
    }
};
```

## Contribution and Support

For discussions, questions, or doubts related to this solution, please visit our [discussion section](https://github.com/getlost01/gfg-potd/discussions). We welcome your input and aim to foster a collaborative learning environment.

If you find this solution helpful, consider supporting us by giving a `⭐ star` to the [getlost01/gfg-potd](https://github.com/getlost01/gfg-potd) repository.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://gl01.gitbook.io/gfg-editorials/2023/06-2023-june-4/05-find-the-closest-element-in-bst.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
