题解 | #牛牛的二叉树问题#
牛牛的二叉树问题
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
List<Integer> list = new ArrayList<>();
Deque<TreeNode> dq = new ArrayDeque<>();
dq.offer(root);
//遍历每一个树节点的值,存入链表中
while(!dq.isEmpty()){
TreeNode cur = dq.poll();
list.add(cur.val);
if(cur.left != null){
dq.offer(cur.left);
}
if(cur.right != null) dq.offer(cur.right);
}
//按照和target的距离从小到大排序
Collections.sort(list, (a, b) -> {
if(Math.abs(a - target) > Math.abs(b - target)){
return 1;
}
else if(Math.abs(a - target) < Math.abs(b - target)){
return -1;
}
return 0;
});
int[] ans = new int[m];
//取出链表前m个数并排序,即为答案
for(int i = 0; i < m; i++) ans[i] = list.get(i);
Arrays.sort(ans);
return ans;
}
}
