1
void makeParent(TreeNode *root, unordered_map<TreeNode *, TreeNode *> &parent) {5
while (q.empty() == false) {6
TreeNode *curr = q.front();9
if (curr->left != NULL) {10
parent[curr->left] = curr;14
if (curr->right != NULL) {15
parent[curr->right] = curr;23
void solve(TreeNode *target, unordered_map<TreeNode *, TreeNode *> &parent,24
unordered_map<TreeNode *, bool> &visited, vector<int> &res, int k) {26
res.push_back(target->val);36
while (q.empty() == false) {38
distance++; // increment distance value for current level of our level41
for (int i = 0; i < count; i++) {42
TreeNode *curr = q.front();45
if (curr->left != NULL && visited[curr->left] == false) {46
visited[curr->left] = true;49
if (distance == k) // when we reach the node at distance = k, push it to res50
res.push_back(curr->left->val);53
if (curr->right != NULL && visited[curr->right] == false) {54
visited[curr->right] = true;57
if (distance == k) // when we reach the node at distance = k, push it to res58
res.push_back(curr->right->val);61
if (parent[curr] && visited[parent[curr]] == false) {62
visited[parent[curr]] = true;65
if (distance == k) // when we reach the node at distance = k, push it to res66
res.push_back(parent[curr]->val);70
if (distance == k) // if in curr iteration all k distances nodes have been76
vector<int> distanceK(TreeNode *root, TreeNode *target, int k) {77
unordered_map<TreeNode *, TreeNode *> parent;78
makeParent(root, parent);80
unordered_map<TreeNode *, bool> visited;83
solve(target, parent, visited, ans, k); // begin from target Node