> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/binary_tree_and_divide_conquer/order-traversal/742.-closest-leaf-in-a-binary-tree.md).

# 742. Closest Leaf in a Binary Tree

Given a binary tree **where every node has a unique value**, and a target key `k`, find the value of the nearest leaf node to target `k` in the tree.

Here, nearest to a leaf means the least number of edges travelled on the binary tree to reach any leaf of the tree. Also, a node is called a leaf if it has no children.

In the following examples, the input tree is represented in flattened form row by row. The actual `root` tree given will be a TreeNode object.

**Example 1:**

```
Input:
root = [1, 3, 2], k = 1
Diagram of binary tree:
          1
         / \
        3   2

Output: 2 (or 3)

Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.
```

**Example 2:**

```
Input:
root = [1], k = 1
Output: 1

Explanation: The nearest leaf node is the root node itself.
```

**Example 3:**

```
Input:
root = [1,2,3,4,null,null,null,5,null,6], k = 2
Diagram of binary tree:
             1
            / \
           2   3
          /
         4
        /
       5
      /
     6

Output: 3
Explanation: The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.
```

**Note:**<br>

1. `root` represents a binary tree with at least `1` node and at most `1000` nodes.
2. Every node has a unique `node.val` in range `[1, 1000]`.
3. There exists some node in the given binary tree for which `node.val == k`.

二叉树每个节点的值是唯一的，找离结点值为K的最近的叶结点。遍历树生成图，从K结点处做BFS直到遇到一个叶结点。

```cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* dfs(TreeNode *cur, unordered_map<TreeNode*, TreeNode*> &edges, int k) {
        if (cur == nullptr) return nullptr;
        if (cur->val == k) return cur;
        if (cur->left != nullptr) {
            edges[cur->left] = cur;
            auto l = dfs(cur->left, edges, k);
            if (l != nullptr) return l;
        }
        if (cur->right != nullptr) {
            edges[cur->right] = cur;
            auto r = dfs(cur->right, edges, k);
            if (r != nullptr) return r;
        }
        return nullptr;
    }
    
    int findClosestLeaf(TreeNode* root, int k) {
        unordered_map<TreeNode*, TreeNode*> edges;
        auto k_node = dfs(root, edges, k);
        if (k_node == nullptr) return -1;
        queue<TreeNode*> q;
        q.push(k_node);
        unordered_set<TreeNode*> visited;
        while (!q.empty()) {
            for (int size = q.size(); size > 0; --size) {
                auto t = q.front(); q.pop();
                if (t->left == nullptr  && t->right == nullptr) return t->val;
                if (visited.count(t)) continue;
                visited.insert(t);
                if (t->left != nullptr) q.push(t->left);
                if (t->right != nullptr) q.push(t->right);
                if (edges.count(t)) q.push(edges[t]);
            }
        }
        return -1;
    }
};
```


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hao-fu-1.gitbook.io/oj/binary_tree_and_divide_conquer/order-traversal/742.-closest-leaf-in-a-binary-tree.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
