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 least 1 node and at most 1000 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.

Tree -----> Graph

  1. First, preform DFS on root in order to find the node whose val = k, at the meantime use HashMap to keep record of all back edges from child to parent;
  2. Then perform BFS on this node to find the closest leaf node.

Note only the nodes visited in DFS are put into the backedgeMap, the others don't. This is fine, cause only from KNode to root this path, we need to check backMap.

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int findClosestLeaf(TreeNode root, int k) {
HashMap<TreeNode, TreeNode> backMap = new HashMap<>(); // store all edges that trace node back to its parent
HashSet<TreeNode> visited = new HashSet<>(); // visited node in BFS
Queue<TreeNode> queue = new LinkedList<>(); // for BFS TreeNode KNode = dfs(root, k, backMap); // DFS: search for node whoes val == k queue.offer(KNode);
visited.add(KNode); while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur.left == null && cur.right == null) {
return cur.val;
}
if (cur.left != null && visited.add(cur.left)) {
queue.offer(cur.left);
}
if (cur.right != null && visited.add(cur.right)) {
queue.offer(cur.right);
}
if (backMap.containsKey(cur) && visited.add(backMap.get(cur))) {
queue.offer(backMap.get(cur));
}
} return -1;
} public TreeNode dfs(TreeNode cur, int k, HashMap<TreeNode, TreeNode> backMap) {
if (cur.val == k) {
return cur;
}
if (cur.left != null) {
TreeNode left = dfs(cur.left, k, backMap);
backMap.put(cur.left, cur);
if (left != null) return left;
}
if (cur.right != null) {
TreeNode right = dfs(cur.right, k, backMap);
backMap.put(cur.right, cur);
if (right != null) return right;
}
return null;
}
}

Leetcode: Closest Leaf in a Binary Tree的更多相关文章

  1. [LeetCode] 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 n ...

  2. LeetCode 742. Closest Leaf in a Binary Tree

    原题链接在这里:https://leetcode.com/problems/closest-leaf-in-a-binary-tree/ 题目: Given a binary tree where e ...

  3. 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 ...

  4. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  5. [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度

    Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shor ...

  6. [LeetCode] 366. Find Leaves of Binary Tree 找二叉树的叶节点

    Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps un ...

  7. LeetCode 111. Minimum Depth of Binary Tree (二叉树最小的深度)

    Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shor ...

  8. LeetCode 104. Maximum Depth of Binary Tree (二叉树的最大深度)

    Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the long ...

  9. LeetCode OJ Minimum Depth of Binary Tree 递归求解

        题目URL:https://leetcode.com/problems/minimum-depth-of-binary-tree/ 111. Minimum Depth of Binary T ...

随机推荐

  1. 以服务方式启动tomcat无法访问NFS共享盘

    用startup.bat方式启动tomcat,程序的可以访问NFS共享盘的文件.但用 1).以服务的方式启动tomcat 2).或者用windows的任务计划去执行startup.bat的方式启动to ...

  2. qt5.12 解决显示中文乱码问题

    在菜单栏   文件->选项,找到文本编辑器 文件编码设置如图 在cpp文件中加入 #pragma execution_character_set("utf-8") 之后就可以 ...

  3. C语言结构体变量字节对齐问题总结

    结构体字节对齐 在用sizeof运算符求算某结构体所占空间时,并不是简单地将结构体中所有元素各自占的空间相加,这里涉及到内存字节对齐的问题.从理论上讲,对于任何 变量的访问都可以从任何地址开始访问,但 ...

  4. P4281 [AHOI2008]紧急集合 / 聚会[LCA]

    解析 蒟蒻用的办法比较蠢,不如上面的各位大佬,直接化成一个式子了,我还是分类讨论做的. 下面正文. 猜想:最优集合点一定是三点任意两对点对应的路径的交点. 不妨这样想,如果任意两个人经过同一条路径,那 ...

  5. nginx 负载均衡,如何判断某台服务器宕机?

    答:使用参数:proxy_connect_timeout: 这个参数是连接的超时时间.设置成1,表示是1秒后超时会连接到另外一台服务器. 配置在 server 部分里.

  6. li的inline-block出现间隙原因,解决方案

    <style type="text/css"> body{ margin:0 0; padding:0 0; font-size: 14; text-decoratio ...

  7. bind的模拟实现

    bind 一句话介绍 bind: bind() 方法会创建一个新函数.当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数.( ...

  8. ie下的透明度,用滤镜filter:alpha

    .box{ width:100px; height:100px; background-color:#000; filter:alpha(Opacity=50); opacity: 0.5; }

  9. Java-Modifier类常用方法详解

    一.Modifier类的定义 Modifier类 (修饰符工具类) 位于 java.lang.reflect 包中,用于判断和获取某个类.变量或方法的修饰符Modifier类将各个修饰符表示为相对应的 ...

  10. Vue——核心思想--mvvm

    Vue的核心思想为数据驱动和组件化. 一.数据驱动——双向绑定 Vue是一种MVVM框架.而DOM是数据的一个种自然映射.传统的模式是通过Ajax请求从model请求数据,然后手动的触发DOM传入数据 ...