zoukankan      html  css  js  c++  java
  • [LeetCode] 863. All Nodes Distance K in Binary Tree

    We are given a binary tree (with root node root), a target node, and an integer value k.

    Return a list of the values of all nodes that have a distance k from the target node.  The answer can be returned in any order.

    Example 1:

    Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
    
    Output: [7,4,1]
    
    Explanation: 
    The nodes that are a distance 2 from the target node (with value 5)
    have values 7, 4, and 1.
    
    
    
    Note that the inputs "root" and "target" are actually TreeNodes.
    The descriptions of the inputs above are just serializations of these objects.

    Note:

    1. The given tree is non-empty.
    2. Each node in the tree has unique values 0 <= node.val <= 500.
    3. The target node is a node in the tree.
    4. 0 <= k <= 1000.

    二叉树中所有距离为 K 的结点。

    给定一个二叉树(具有根结点 root), 一个目标结点 target ,和一个整数值 K 。

    返回到目标结点 target 距离为 K 的所有结点的值的列表。 答案可以以任何顺序返回。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/all-nodes-distance-k-in-binary-tree
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这道题非常好,是一道树 tree 和图论 graph 的结合题。这里我提供一个 BFS 的做法。

    题目给的 input 是树,但是我们是需要把他转译成图才能做的,这样我们才能既可以知道父节点的邻居有子节点,也可以知道子节点的邻居有父节点。知道这些信息之后,我们从 target 节点开始做 BFS 遍历。因为题目找的是距离 target 节点长度为 K 的节点,所以我们在开始 BFS 遍历的同时,要记得 K--。这样当 K = 0 的时候,如果此时 queue 中有元素,这些元素就都是相距 target 节点,距离为 K 的节点。

    时间O(n)

    空间O(n)

    Java实现

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution {
    11     HashMap<TreeNode, List<TreeNode>> map = new HashMap<>();
    12     
    13     public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
    14         List<Integer> res = new ArrayList<>();
    15         
    16         // build the graph
    17         buildGraph(root, null);
    18         
    19         // corner case
    20         if (!map.containsKey(target)) {
    21             return res;
    22         }
    23         
    24         HashSet<TreeNode> visited = new HashSet<>();
    25         Queue<TreeNode> queue = new LinkedList<>();
    26         visited.add(target);
    27         queue.offer(target);
    28         while (!queue.isEmpty()) {
    29             int size = queue.size();
    30             // 抵达终点
    31             if (K == 0) {
    32                 for (int i = 0; i < size; i++) {
    33                     TreeNode cur = queue.poll();
    34                     res.add(cur.val);
    35                 }
    36                 return res;
    37             }
    38             
    39             // 在路上
    40             for (int i = 0; i < size; i++) {
    41                 TreeNode cur = queue.poll();
    42                 for (TreeNode next : map.get(cur)) {
    43                     if (visited.contains(next)) {
    44                         continue;
    45                     }
    46                     visited.add(next);
    47                     queue.offer(next);
    48                 }
    49             }
    50             K--;
    51         }
    52         return res;
    53     }
    54     
    55     // 类似前序遍历的方式创建图
    56     private void buildGraph(TreeNode node, TreeNode parent) {
    57         // base case
    58         if (node == null) {
    59             return;
    60         }
    61         if (!map.containsKey(node)) {
    62             map.put(node, new ArrayList<>());
    63             if (parent != null) {
    64                 map.get(node).add(parent);
    65                 map.get(parent).add(node);
    66             }
    67             buildGraph(node.left, node);
    68             buildGraph(node.right, node);
    69         }
    70     }
    71 }

    LeetCode 题目总结

  • 相关阅读:
    [GSEAPY] 在Python里进行基因集富集分析
    scRNAseq R包公共单细胞数据获取
    pybedtools:在Python中使用BEDTools
    pybedtools 提取序列
    将博客搬至CSDN
    【转】SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
    sql长日期数据以短日期格式显示【转】
    [转]YouTube架构学习体会
    [转]让Nginx 支持 ASP ASP.NET配置方法
    [转]LINQ查询总结
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14783291.html
Copyright © 2011-2022 走看看