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也是同理。
易错点:
- find parent当中不要把nullptr也map进去。
- 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;
}
};