给定一个 每个结点的值互不相同 的二叉树,和一个目标值 k,找出树中与目标值 k 最近的叶结点。
这里,与叶结点 最近 表示在二叉树中到达该叶节点需要行进的边数与到达其它叶结点相比最少。 而且,当一个结点没有孩子结点时称其为叶结点。
在下面的例子中,输入的树以逐行的平铺形式表示。 实际上的有根树 root 将以TreeNode对象的形式给出。
示例 1:
输入:
root = [1, 3, 2], k = 1
二叉树图示:
1
/ \
3 2
输出: 2 (或 3)
解释: 2 和 3 都是距离目标 1 最近的叶节点。
示例 2:
输入:
root = [1], k = 1
输出:1
解释: 最近的叶节点是根结点自身。
示例 3:
输入:
root = [1,2,3,4,null,null,null,5,null,6], k = 2
二叉树图示:
1
/ \
2 3
/
4
/
5
/
6
输出:3
解释: 值为 3(而不是值为 6)的叶节点是距离结点 2 的最近结点。
注:
root 表示的二叉树最少有 1 个结点且最多有 1000 个结点。
每个结点都有一个唯一的 node.val ,范围为 [1, 1000]。
给定的二叉树中有某个结点使得 node.val == k。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/closest-leaf-in-a-binary-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
unordered_map<TreeNode*,TreeNode*> father;
queue<TreeNode*> q;
unordered_set<TreeNode*> visited;
public:
int findClosestLeaf(TreeNode* root, int k) {
father[root] = NULL;
dfs(root, k);
int size;
TreeNode* cur;
while(!q.empty())
{
size = q.size();
while(size--)
{
cur = q.front();
q.pop();
if(!cur->left && !cur->right)
return cur->val;
if(cur->left && !visited.count(cur->left))
{
q.push(cur->left);
visited.insert(cur->left);
}
if(cur->right && !visited.count(cur->right))
{
q.push(cur->right);
visited.insert(cur->right);
}
if(father[cur] && !visited.count(father[cur]))
{
q.push(father[cur]);
visited.insert(father[cur]);
}
}
}
return -1;
}
void dfs(TreeNode* root, int k)
{
if(!root) return;
if(root->val == k)
{
q.push(root);
visited.insert(root);
}
if(root->left)
father[root->left] = root;
if(root->right)
father[root->right] = root;
dfs(root->left,k);
dfs(root->right,k);
}
};
28 ms 22.9 MB