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. OSPF 多区域配置

    通过配置OSPF协议使网络互通. 实验拓扑 如图所示连接,地址规划如下: 名称 接口 IP地址 R1 f1/0 192.168.10.1/24 R1 f0/0 192.168.20.1/24 R1 f ...

  2. centos 长久路由表

    由于用命令添加路由条目之后,重启程序后,条目会消失.所以需要用文件管理路由. 1.根据网卡创建路由表文件 vim /etc/sysconfig/network-scripts/route-eth0 2 ...

  3. JVM存储位置分配——java中局部变量、实例变量和静态变量在方法区、栈内存、堆内存中的分配

    Java中的变量根据不同的标准可以分为两类,以其引用的数据类型的不同来划分可分为“原始数据类型变量和引用数据类型变量”,以其作用范围的不同来区分可分为“局部变量,实例变量和静态变量”. 根据“Java ...

  4. Codeforces K. Ice Skating(求强连通分量)

    题目描述: Ice Skating time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...

  5. Find the median(2019年牛客多校第七场E题+左闭右开线段树)

    题目链接 传送门 题意 每次往集合里面添加一段连续区间的数,然后询问当前集合内的中位数. 思路 思路很好想,但是卡内存. 当时写的动态开点线段树没卡过去,赛后机房大佬用动态开点过了,\(tql\). ...

  6. 2019年杭电多校第二场 1012题Longest Subarray(HDU6602+线段树)

    题目链接 传送门 题意 要你找一个最长的区间使得区间内每一个数出现次数都大于等于\(K\). 思路 我们通过固定右端点考虑每个左端点的情况. 首先对于每个位置,我们用线段树来维护它作为\(C\)种元素 ...

  7. javascript---call,apply,bind

    对于这三个函数,估计大家都还是很模糊,具体是用来干什么?简而言之,是用来对象冒充的. 首先这三个方法是每个函数都包含的非继承的的方法. 我来搬砖一下,此文引用 http://www.cnblogs.c ...

  8. 配置/更改vue项目中的资源路径

    打开 build/webpack.base.conf.js  ,在module.exports .resolve.alias下自定义: alias: { 'vue$': 'vue/dist/vue.e ...

  9. 20180429模拟赛T1——添边问题

    [问题描述] 没有环的有向图称为有向无环图,这是一个多么美好的结构吖. 如果有一张有 N 个点的有向图,我们可能需要删掉一些边使它变成一张有向无环图.假设初始时我们只有 N 个互不相连的点,当然它也是 ...

  10. spark运行时加载配置文件(hive,hdfs)

    文章为转载,如有版权问题,请联系,谢谢! 转自:https://blog.csdn.net/piduzi/article/details/81636253 适合场景:在运行时才确定用哪个数据源 imp ...