863. All Nodes Distance K in Binary Tree

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:

The given tree is non-empty.
Each node in the tree has unique values 0 <= node.val <= 500.
The target node is a node in the tree.
0 <= K <= 1000.

方法1: hash + dfs

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

思路:

如果转变成graph的话, 这道题标准的dfs/bfs可以解决。虽然树也是特殊的有向图,但不能从子节点向上返回,就为往上找K邻居和表亲增加了困难。那么最直接的方法就是弥补这些连接,方法有很多种,可以新建一个adj list完全重建所有的edge,并添加逆向连接。图建好后,可以用dfs/bfs来找k距离以外的邻居。由于变成了无向图,必须用一个visited的hashset来记录路径,避免成环。这里第一种方法选择不完全重建整个graph,而是用hashmap将child -> parent的edge补上,在dfs的过程中向当前节点的left, right, parent三个方向发起递归。bfs也是同理。

易错点:

  1. find parent当中不要把nullptr也map进去。
  2. visited记录的位置:事实证明放在推result之前还是之后其实都可以。

Complexity

Time complexity: O(n)
Space complexity: O(n)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
        unordered_map<TreeNode*, TreeNode*> parent; // child -> parent
        unordered_set<TreeNode*> visited;
        vector<int> result;
        findParent(root, parent);
        distHelper(target, K, result, parent, visited);
        return result;
    }
    
    void distHelper(TreeNode* root, int K, vector<int> & result,  unordered_map<TreeNode*, TreeNode*> & parent, unordered_set<TreeNode*> & visited) {
        if (!root) return;
        visited.insert(root);
        if (K == 0) {
            result.push_back(root -> val); 
            return;
        }
        if (!visited.count(root -> left)) 
            distHelper(root -> left, K - 1, result, parent, visited);
        if (!visited.count(root -> right))
            distHelper(root -> right, K - 1, result, parent, visited);
        if (parent.count(root) && !visited.count(parent[root]))
            distHelper(parent[root], K - 1, result, parent, visited);
        return;
    }
    
    void findParent(TreeNode* root, unordered_map<TreeNode*, TreeNode*> & parent){
        if (!root) return;
        // dont map nullptr children
        if (root -> left) parent[root -> left] = root;
        if (root -> right) parent[root -> right] = root;
        findParent(root -> left, parent);
        findParent(root -> right, parent);
        return;
    } 
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值