我需要使用BFS在二叉树中打印大于给定数字(我们可以称其为“ k”)的最小级别的节点值。
答案 0 :(得分:0)
public static void printBiggerMinLevel(Node root, int k) {//Using BFS
int chosen = 0, level = Integer.MAX_VALUE;
if(root == null) return;
if(root.getVal() > k) {
System.out.println(root.getVal());
return;
}
Queue<Node> q = new Queue<>();
q.enqueue(root);
Node cur;
while(!q.isEmpty()) {
cur = q.dequeue();
if(cur.getVal() > k)
if(cur.getLevel() < level) {
chosen = cur.getVal();
level = cur.getLevel();
}
if(cur.getLeftSon() != null)
q.enqueue(cur.getLeftSon());
if(cur.getRightSon() != null)
q.enqueue(cur.getRightSon());
}
System.out.println(chosen);
}