【问题标题】:Get level with most occurrences in a binary tree获取二叉树中出现次数最多的级别
【发布时间】:2023-01-22 21:09:07
【问题描述】:

我需要填写此函数,以便在二叉树中找到某个数字出现次数最多的级别。但是我不能使用任何辅助函数。

公共课 LevelMostOccurrences { public static int getLevelWithMostOccurrences(BinNode root, int num) {

}

enter image description here

【问题讨论】:

    标签: java


    【解决方案1】:

    您可以使用广度优先搜索算法遍历二叉树并跟踪给定数字的级别和出现次数。您可以使用队列来跟踪要访问的节点,并使用变量来存储当前级别。在 while 循环内,从队列中取出一个节点,检查它是否是给定的数字,如果是则递增计数。然后,将它的孩子添加到队列中并增加级别。在遍历结束时,返回给定数字出现次数最多的级别。

    public static int getLevelWithMostOccurrences(BinNode root, int num) {
        if (root == null) {
            return -1;
        }
        Queue<BinNode> queue = new LinkedList<>();
        queue.offer(root);
        int level = 0;
        int maxCount = 0;
        int maxLevel = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            int count = 0;
            for (int i = 0; i < size; i++) {
                BinNode curr = queue.poll();
                if (curr.val == num) {
                    count++;
                }
                if (curr.left != null) {
                    queue.offer(curr.left);
                }
                if (curr.right != null) {
                    queue.offer(curr.right);
                }
            }
            if (count > maxCount) {
                maxCount = count;
                maxLevel = level;
            }
            level++;
        }
        return maxLevel;
    }
    

    【讨论】:

    • 这是一个很好的答案 - 但你是否意识到你刚刚为他们完成了某人的家庭作业?他们不会以这种方式学到任何东西——这就是(部分原因)为什么我们通常要求他们至少表现出一些努力并首先尝试自己解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    相关资源
    最近更新 更多