Approach
Depth-first search
For All Nodes Distance K in Binary Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 48 lines of C++ from the credited upstream file 863.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {4 vector<int> ans;5 unordered_map<TreeNode*, int> nodeToDist; 6 7 getDists(root, target, nodeToDist);8 dfs(root, k, 0, nodeToDist, ans);9 return ans;10 }11 12 private:13 void getDists(TreeNode* root, TreeNode* target,14 unordered_map<TreeNode*, int>& nodeToDist) {15 if (root == nullptr)16 return;17 if (root == target) {18 nodeToDist[root] = 0;19 return;20 }21 22 getDists(root->left, target, nodeToDist);23 if (const auto it = nodeToDist.find(root->left); it != nodeToDist.cend()) {24 25 nodeToDist[root] = it->second + 1;26 return;27 }28 29 getDists(root->right, target, nodeToDist);30 if (const auto it = nodeToDist.find(root->right); it != nodeToDist.cend())31 32 nodeToDist[root] = it->second + 1;33 }34 35 void dfs(TreeNode* root, int k, int dist,36 unordered_map<TreeNode*, int>& nodeToDist, vector<int>& ans) {37 if (root == nullptr)38 return;39 if (const auto it = nodeToDist.find(root); it != nodeToDist.cend())40 dist = it->second;41 if (dist == k)42 ans.push_back(root->val);43 44 dfs(root->left, k, dist + 1, nodeToDist, ans);45 dfs(root->right, k, dist + 1, nodeToDist, ans);46 }47};48