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

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

没啥思路,以为是dfs就可以了。但是其实分为两步:

存储:把root,左右长度存在map中

取出来:length每次加一,递增为k

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. map中存的距离是找出left之后,left+1
  2. 在map中找root之前要先判断是否有这个key

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

先在左边右边用dfs生成长度,存map。再用dfs的length+1找出所有节点

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

int left = find(root.left, target, K);
        if (left >= 0) {
            map.put(root, left + 1);
            return left + 1;
        }

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

[是否头一次写此类driver funcion的代码] :

[潜台词] :

class Solution {
    //initialization: hashmap
    HashMap<TreeNode, Integer> map = new HashMap<TreeNode, Integer>();

    public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
        List<Integer> result = new ArrayList<Integer>();
        find(root, target, K);
        dfs(root, 0, target, K, result);
        return result;
    }

    //find and store length
    public int find(TreeNode root, TreeNode target, int K) {
        //corner case: root == null
        if (root == null) return -1;

        //root.val == target
        if (target == root) {
            map.put(root, 0);
            return 0;
        }

        //define left, right and add
        int left = find(root.left, target, K);
        if (left >= 0) {
            map.put(root, left + 1);
            return left + 1;
        }
        int right = find(root.right, target, K);
        if (right >= 0) {
            map.put(root, right + 1);
            return right + 1;
        }

        return -1;
    }

    //add the points to res
    public void dfs(TreeNode root, int length, TreeNode target, int K, List<Integer> res) {
        //corner case
        if (root == null) return ; 

        //get length if there is key
        if (map.containsKey(root)) {
            length = map.get(root);
        }
        //add to res
        if (length == K) res.add(root.val); 

        //dfs in left and right
        dfs(root.left, length + 1, target, K, res);
        dfs(root.right, length + 1, target, K, res);
    }
}

原文地址:https://www.cnblogs.com/immiao0319/p/9596109.html

时间: 2024-08-27 13:21:44

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

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

863.&#160;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<TreeNo

[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

Leetcode 226 Invert Binary Tree python

题目: Invert a binary tree. 翻转二叉树. 递归,每次对节点的左右节点调用invertTree函数,直到叶节点. python中也没有swap函数,当然你可以写一个,不过python中可以通过:a, b = b, a交换两个变量的值 1 class Solution(object): 2 def invertTree(self, root): 3 if root == None: return root 4 root.left, root.right = self.inve

笔试算法题(41):线索二叉树(Threaded Binary Tree)

出题:线索二叉树(Threaded Binary Tree) 分析: 为除第一个节点外的每个节点添加一个指向其前驱节点的指针,为除最后一个节点外的每个节点添加一个指向其后续节点的指针,通过这些额外的指针可以某种遍历方式对二叉树进行遍历,而加了这些额外指针的二叉树就是线索二叉树: 对于含有N个节点的二叉树而言,一共有2N个指针,但除了根节点的其他节点都有来自其父节点的指针,所以耗用了N-1个指针,则最终剩下2N-(N- 1)=N+1个空指针:线索二叉树就是利用这些空指针存储具有某种遍历顺序的前驱和