繁体   English   中英

如何使用 BFS 在二叉树中打印大于给定数字的最小级别节点?

[英]How to print the minimum level node that is bigger than a given number in Binary Tree using BFS?

我需要使用 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);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM