<p>Given the <code>root</code> of a binary tree, the value of a target node <code>target</code>, and an integer <code>k</code>, return <em>an array of the values of all nodes that have a distance </em><code>k</code><em> from the target node.</em></p>

<p>You can return the answer in <strong>any order</strong>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/28/sketch0.png" style="width: 500px; height: 429px;" />
<pre>
<strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
<strong>Output:</strong> [7,4,1]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> root = [1], target = 1, k = 3
<strong>Output:</strong> []
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 500]</code>.</li>
	<li><code>0 &lt;= Node.val &lt;= 500</code></li>
	<li>All the values <code>Node.val</code> are <strong>unique</strong>.</li>
	<li><code>target</code> is the value of one of the nodes in the tree.</li>
	<li><code>0 &lt;= k &lt;= 1000</code></li>
</ul>

class Solution {


unordered_map<TreeNode*, TreeNode*> pa;

// get immediate parent of every node
void dfs(TreeNode* rt) {
	if (rt->left != NULL) {
		pa[rt->left] = rt;
		dfs(rt->left);
	}
	if (rt->right != NULL) {
		pa[rt->right] = rt;
		dfs(rt->right);
	}
}

public:
    vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
    	dfs(root);
		pa[root] = NULL;
		unordered_map<TreeNode*, int> dis; // calculate distance from target node to all parents / ancestors till root
		TreeNode* u = target;
		int d = 0;
		while (u != NULL) {
			dis[u] = d;
			u = pa[u];
			d++;
		}    
		queue<pair<TreeNode*, int>> q; // {node, dis}
		q.push({root, dis[root]});

		// while doing BFS, override distances of nodes with the distance in parent distance map, if present.		

		vector<int> ans;

		while (!q.empty()) {
			pair<TreeNode*, int> p = q.front();
			q.pop();
			TreeNode* n = p.first;
			d = p.second;
			auto it = dis.find(n);
			if (it != dis.end()) {
				d = it->second;
			}
			if (d == k) {
				ans.push_back(n->val);
			}
			if (n->left != NULL) {
				q.push({n->left, 1 + d});
			}
			if (n->right != NULL) {
				q.push({n->right, 1 + d});
			}
		}
		return ans;
     }
};


14300