742. Closest Leaf in a Binary Tree
https://leetcode.com/problems/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:
root
represents a binary tree with at least1
node and at most1000
nodes.Every node has a unique
node.val
in range[1, 1000]
.There exists some node in the given binary tree for which
node.val == k
.
二叉树每个节点的值是唯一的,找离结点值为K的最近的叶结点。遍历树生成图,从K结点处做BFS直到遇到一个叶结点。
/**
* 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;
}
};
Last updated
Was this helpful?