剑指offer 2021/7/29

本文介绍了两种不同的二叉树镜像实现方法,包括使用BFS遍历交换节点子树以及递归交换。同时,探讨了三种找出数组中出现次数超过一半数字的算法,包括哈希计数、排序查找和摩尔投票法。这些算法在解决实际问题中具有重要意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

27. 二叉树的镜像

bfs遍历整个二叉树,并将节点的左右子树互换。

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null)
            return null;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            exchange(node);
            if(node.left != null){
                queue.add(node.left);
            }
            if(node.right != null){
                queue.add(node.right);
            }
        }
        return root;
    }
    void exchange(TreeNode node){
        TreeNode temp;
        temp = node.left;
        node.left = node.right;
        node.right = temp;
    }
}

法二:

BFS

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null){
            return null;
        }
        TreeNode left = mirrorTree(root.right);
        TreeNode right = mirrorTree(root.left);
        root.left = left;
        root.right = right;
        return root;
    }
}

39. 数组中出现次数超过一半的数字

代码:

用哈希表记录元素出现次数。

class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; ++i){
            map.put(nums[i], map.getOrDefault(nums[i], 0)+1);
            if(map.get(nums[i]) > nums.length/2){
                return nums[i];
            }
        }
        return 0;
    }
}

改进1:

将数组 nums 排序,数组中点的元素 一定为众数。

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}

改进2:

摩尔投票法
初始化vote=0,遍历数组,当vote=0时,将该数组元素赋给x作为众数。若当前数组元素等于x,vote+1,否则-1。

class Solution {
    public int majorityElement(int[] nums) {
        int x = 0, vote = 0;
        for(int num : nums){
            if(vote == 0){
                x = num;
            }
            vote += num == x ? 1 : -1;
        }
        return x;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值