[LeetCode] Closest Leaf in a Binary Tree

742. Closest Leaf in a Binary Tree

Given the root of a binary tree where every node has a unique value and a target integer k, return the value of the nearest leaf node to the target k in the tree.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
unordered_map<int, pair<int, int>> mp;
pair<int, int> dfs(TreeNode* node) {
if(!node->left and !node->right) {
mp[node->val] = {0, node->val};
return {1, node->val};
}
mp[node->val] = {INT_MAX, INT_MAX};
if(node->left) {
auto [d, v] = dfs(node->left);
if(mp[node->val].first > d) mp[node->val] = {d, v};
}
if(node->right) {
auto [d, v] = dfs(node->right);
if(mp[node->val].first > d) mp[node->val] = {d, v};
}

return {mp[node->val].first + 1, mp[node->val].second};
}
void dfs2(TreeNode* node, int par) {
if(!node) return;
auto v = node->val;
if(mp[v].first > mp[par].first + 1) {
mp[v] = mp[par];
mp[v].first++;
}
dfs2(node->left, v);
dfs2(node->right, v);
}
public:
int findClosestLeaf(TreeNode* root, int k) {
mp[-1] = {INT_MAX - 1, INT_MAX - 1};
dfs(root);
dfs2(root, -1);
return mp[k].second;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/23/PS/LeetCode/closest-leaf-in-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.