题解 | #牛牛的二叉树问题#
牛牛的二叉树问题
https://www.nowcoder.com/practice/1b80046da95841a9b648b10f1106b04e
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param target double浮点型 * @param m int整型 * @return int整型一维数组 */ public int[] findClosestElements (TreeNode root, double target, int m) { // write code here Map<Double, List<Integer>> allNodes = new TreeMap<>(); preorderAdd(root, allNodes, target); List<Integer> resultList = new ArrayList<>(); allNodes.values().stream().flatMap(List::stream).forEach(resultList::add); resultList = resultList.subList(0,m); int[] results = resultList.stream().mapToInt(Integer::valueOf).toArray(); Arrays.sort(results); return results; } public void preorderAdd(TreeNode root, Map<Double, List<Integer>> allNodes, double target){ if (root == null) return; Double absDiff = Math.abs(root.val-target); if (allNodes.get(absDiff) == null){ allNodes.put(absDiff, new ArrayList<>()); } List<Integer> tempL = allNodes.get(absDiff); tempL.add(root.val); allNodes.put(absDiff, tempL); Collections.sort(tempL); preorderAdd(root.left, allNodes, target); preorderAdd(root.right, allNodes, target); } }