我需要使用 BFS 打印大于给定数字(我们可以称之为“k”)的二叉树中最小级别的节点值。
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.