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
- 46 lines of Java from the credited upstream file 863.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 List<Integer> distanceK(TreeNode root, TreeNode target, int k) {3 List<Integer> ans = new ArrayList<>();4 Map<TreeNode, Integer> nodeToDist = new HashMap<>(); 5 6 getDists(root, target, nodeToDist);7 dfs(root, k, 0, nodeToDist, ans);8 9 return ans;10 }11 12 private void getDists(TreeNode root, TreeNode target, Map<TreeNode, Integer> nodeToDist) {13 if (root == null)14 return;15 if (root == target) {16 nodeToDist.put(root, 0);17 return;18 }19 20 getDists(root.left, target, nodeToDist);21 if (nodeToDist.containsKey(root.left)) {22 23 nodeToDist.put(root, nodeToDist.get(root.left) + 1);24 return;25 }26 27 getDists(root.right, target, nodeToDist);28 if (nodeToDist.containsKey(root.right))29 30 nodeToDist.put(root, nodeToDist.get(root.right) + 1);31 }32 33 private void dfs(TreeNode root, int k, int dist, Map<TreeNode, Integer> nodeToDist,34 List<Integer> ans) {35 if (root == null)36 return;37 if (nodeToDist.containsKey(root))38 dist = nodeToDist.get(root);39 if (dist == k)40 ans.add(root.val);41 42 dfs(root.left, k, dist + 1, nodeToDist, ans);43 dfs(root.right, k, dist + 1, nodeToDist, ans);44 }45}46