863. All Nodes Distance K in Binary Tree

https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/143752/JAVA-Graph-+-BFS

https://www.youtube.com/watch?v=o1siL8eKCos

class Solution {
    Map<TreeNode, List<TreeNode>> map = new HashMap();
//here can also use Map<TreeNode, TreeNode> to only store the child - parent mapping, since parent-child mapping is inherent in the tree structure

    public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
         List<Integer> res = new ArrayList<Integer> ();
        if (root == null || K < 0) return res;
        buildMap(root, null);
        if (!map.containsKey(target)) return res;
        Set<TreeNode> visited = new HashSet<TreeNode>();
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.add(target);
        visited.add(target);
        while (!q.isEmpty()) {
            int size = q.size();
            if (K == 0) {
                for (int i = 0; i < size ; i++) res.add(q.poll().val);
                return res;
            }
            for (int i = 0; i < size; i++) {
                TreeNode node = q.poll();
                for (TreeNode next : map.get(node)) {
                    if(visited.add(next)){
                        q.offer(next);
                    }
                }
            }
            K--;
        }
        return res;
    }

    private void buildMap(TreeNode node, TreeNode parent) {
        if (node == null) return;
        if (!map.containsKey(node)) {
            map.put(node, new ArrayList<TreeNode>());
            if (parent != null)  { map.get(node).add(parent); map.get(parent).add(node) ; }
            buildMap(node.left, node);
            buildMap(node.right, node);
        }
    }
}

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.

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9929780.html

时间: 2024-10-07 01:19:37

863. All Nodes Distance K in Binary Tree的相关文章

863. All Nodes Distance K in Binary Tree 到制定节点距离为k的节点

[抄题]: 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

the longest distance of a binary tree

个人信息:就读于燕大本科软件工程专业 目前大三; 本人博客:google搜索"cqs_2012"即可; 个人爱好:酷爱数据结构和算法,希望将来从事算法工作为人民作出自己的贡献; 博客内容:the longest distance of a binary tree; 博客时间:2014-4-15; 编程语言:C++ ; 编程坏境:Windows 7 专业版 x64; 编程工具:vs2008 32位编译器; 制图工具:office 2010 ppt; 硬件信息:7G-3 笔记本; my w

[GeeksForGeeks] Remove all half nodes of a given binary tree

Given A binary Tree, how do you remove all the half nodes (which has only one child)? Note leaves should not be touched as they have both children as NULL. For example consider the below tree. Nodes 7, 5 and 9 are half nodes as one of their child is

[lintcode] Binary Tree Inorder Traversal

Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' values. Example Given binary tree {1,#,2,3}, 1 2 / 3 return [1,3,2]. SOLUTION 1: 递归方法,具体代码可以参照preorder traversal,这里就不赘述了. SOLUTION 2: 分治法,Divide & conquer,其

LintCode : Binary Tree Path Sum

Description: Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target. A valid path is from root node to any of the leaf nodes. Example: Given a binary tree, and target = 5: 1 / 2 4 / 2 3 return [ [1, 2, 2

Binary Tree Path Sum

Question:  Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target. A valid path is from root node to any of the leaf nodes. Example: Given a binary tree, and target = 5: 1 / 2 4 / 2 3 return [ [1, 2, 2],

Full Binary Tree(GCJ2014 round1A PB)

去年google code jam第一轮的B题,我没有想明白,也没有找到题解.没有办法,就去下载了大神的代码来看看.感觉差距好大,别人用十分钟不到就做出来了.题目的描述如下,我就不写翻译了,题意挺明了的.由于墙的原因,我还是把题目贴下面吧! 题目内容 A tree is a connected graph with no cycles. A rooted tree is a tree in which one special vertex is called the root. If there

Print all nodes at distance k from a given node

Given a binary tree, a target node in the binary tree, and an integer value k, print all the nodes that are at distance k from the given target node. No parent pointers are available Consider the tree shown in diagram Input: target = pointer to node

leetcode day4 -- Binary Tree Postorder(Preorder) Traversal &amp;&amp; Edit Distance

 1.Binary Tree Postorder Traversal Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 2 / 3 return [3,2,1]. Note: Recursive solution is trivial, could you do it iteratively? 分析:后续遍历