Java DFS+BFS modular solution, good for interview
Sharing a solution that could be good for interview. Having methods modularized could be good for speed during the interview and also showcase your industry ski
Sharing a solution that could be good for interview. Having methods modularized could be good for speed during the interview and also showcase your industry skills.\n\n```\nclass Solution {\n    Map<TreeNode, TreeNode> map;\n    public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {\n        map = new HashMap<>();\n        List<Integer> res = new ArrayList<>();\n        traverse(root, null);\n        Deque<TreeNode> q = new ArrayDeque<>();\n        Set<TreeNode> visited = new HashSet<>();\n        q.offer(target);\n        visited.add(target);\n        \n        while (!q.isEmpty() && K >= 0) {\n            int size = q.size();\n            for (int i = 0; i < size; i++) {\n                TreeNode curr = q.poll();\n                if (K == 0) {\n                    res.add(curr.val);\n                }\n                TreeNode l = curr.left;\n                TreeNode r = curr.right;\n                TreeNode p = map.get(curr);\n                if (l != null && visited.add(l)) {\n                    q.offer(l);\n                }\n                if (r != null && visited.add(r)) {\n                    q.offer(r);\n                }\n                if (p != null && visited.add(p)) {\n                    q.offer(p);\n                }\n            }\n            K--;\n        }\n        \n        return res;\n    }\n    \n\t// Template for preorder tranveral and find a node\n    public TreeNode find(TreeNode root, TreeNode target) {\n        if (root == null) {\n            return null;\n        }\n        if (root.val == target.val) {\n            return root;\n        }\n        TreeNode left = find(root.left, target);\n        if (left != null) {\n            return left;\n        }\n        return find(root.right, target);\n    }\n\n    // Template for preorder traversal of the tree\n    public void traverse(TreeNode root, TreeNode parent) {\n        if (root == null) {\n            return;\n        }\n        map.put(root, parent);\n        traverse(root.left, root);\n        traverse(root.right, root);\n    }\n}
[]