题解 | #牛牛的二叉树问题#
牛牛的二叉树问题
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整型一维数组 */ private List<TreeNode> list = new ArrayList<>(); public int[] findClosestElements (TreeNode root, double target, int m) { // write code here dfs(root); Collections.sort(list, (a, b) -> { return (int)(Math.abs(a.val - target) - Math.abs(b.val - target)); }); int[] res = new int[m]; for(int i = 0; i < m; i++){ res[i] = list.get(i).val; } Arrays.sort(res); return res; } public void dfs(TreeNode root){ // System.out.print(root.val); if(root == null) return ; list.add(root); dfs(root.left); dfs(root.right); } }