• [LeetCode] 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 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:

    1. root represents a binary tree with at least 1 node and at most 1000 nodes.
    2. Every node has a unique node.val in range [1, 1000].
    3. There exists some node in the given binary tree for which node.val == k.

    二叉树最近的叶节点。

    给定一个 每个结点的值互不相同 的二叉树,和一个目标值 k,找出树中与目标值 k 最近的叶结点。 

    这里,与叶结点 最近 表示在二叉树中到达该叶节点需要行进的边数与到达其它叶结点相比最少。而且,当一个结点没有孩子结点时称其为叶结点。

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

    给的是一个只有unique value的二叉树,而且还不是二叉搜索树(BST),所以没有办法利用到任何关于BST的办法来解决这个问题。如果我们还是单纯地以一棵树来考量这道题,做法会比较麻烦。当你找到了目标值K所在的节点target之后,分如下两种情况

    • target自己就是一个叶子节点,直接返回0即可
    • target不是叶子节点,对于tree中的所有叶子节点,需要计算target到这些叶子节点的距离,然后去其中的最小值

    一个比较好的思路是把tree变成graph来考虑这道题,并且利用BFS找到距离最近的节点。如果当我们在寻找target节点的过程中,我们用一个hashmap记录<node, parentNode>,这样每个节点的父亲节点也能被访问到。之后我们从target node开始,用BFS的方式遍历整棵树。因为BFS是帮助找图/树中最短距离的方法,所以最先找到的叶子节点(自己没有左右孩子的节点)就是离target距离最近的叶子节点。对于每一个节点node来说,我们不光要看一下他的左右孩子是否被访问过,我们也要看一下他的parent node是否被访问过。如果最后还是找不到则return -1。

    时间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() {}
     8  *     TreeNode(int val) { this.val = val; }
     9  *     TreeNode(int val, TreeNode left, TreeNode right) {
    10  *         this.val = val;
    11  *         this.left = left;
    12  *         this.right = right;
    13  *     }
    14  * }
    15  */
    16 class Solution {
    17     TreeNode target;
    18 
    19     public int findClosestLeaf(TreeNode root, int k) {
    20         HashMap<TreeNode, TreeNode> map = new HashMap<>();
    21         dfs(root, null, map, k);
    22         if (target == null) {
    23             return -1;
    24         }
    25 
    26         Queue<TreeNode> queue = new LinkedList<>();
    27         HashSet<Integer> visited = new HashSet<>();
    28         queue.offer(target);
    29         visited.add(k);
    30         while (!queue.isEmpty()) {
    31             TreeNode cur = queue.poll();
    32             if (cur.left == null && cur.right == null) {
    33                 return cur.val;
    34             }
    35             if (cur.left != null && !visited.contains(cur.left.val)) {
    36                 queue.offer(cur.left);
    37                 visited.add(cur.left.val);
    38             }
    39             if (cur.right != null && !visited.contains(cur.right.val)) {
    40                 queue.offer(cur.right);
    41                 visited.add(cur.right.val);
    42             }
    43             if (map.containsKey(cur) && !visited.contains(map.get(cur).val)) {
    44                 queue.offer(map.get(cur));
    45                 visited.add(map.get(cur).val);
    46             }
    47         }
    48         return -1;
    49     }
    50 
    51     private void dfs(TreeNode root, TreeNode parent, HashMap<TreeNode, TreeNode> map, int k) {
    52         if (root == null) {
    53             return;
    54         }
    55         if (parent != null) {
    56             map.put(root, parent);
    57         }
    58         if (root.val == k) {
    59             target = root;
    60         }
    61         dfs(root.left, root, map, k);
    62         dfs(root.right, root, map, k);
    63     }
    64 }

    LeetCode 题目总结

  • 相关阅读:
    SQL注入详解
    Nginx跨域及Https配置
    GET请求和POST请求的request和response的中文乱码问题
    创建Maven工程
    Maven环境变量配置
    Cookie&Session会话技术
    Maven库站
    20191002思维导图工具MindManager 000 033
    20190930-02 Redis持久化方式一:RDB及修改RDB的默认持久化策略 000 032
    Tomcat配置HTTPS方式生成安全证书
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14088331.html
Copyright © 2020-2023  润新知