二叉树镜像问题

今天写了剑指offer中的二叉树镜像问题,写到第三种解法的时候遇到了一个关于ArrayDeque的问题,将其记录下来
题目如下
思路:镜像就是将“根”节点的左右两个“子”节点互换
解法一:

/**
     * 递归
     * @param root
     */
    public static void Mirror1(TreeNode root) {
        if(root == null || (root.left == null&&root.right == null))return;
        TreeNode pTree = root.left;
        root.left = root.right;
        root.right = pTree;
        Mirror1(root.left);
        Mirror1(root.right);
    }

解法二:

/**
     * 二叉树深度搜索
     * @param root
     */
    public static void Mirror2(TreeNode root) {
        if(root == null || (root.left == null&&root.right == null))return;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode pTree,curTree;
        while (!stack.isEmpty()) {
            curTree = stack.pop();
            if(curTree == null || (curTree.left == null&&curTree.right == null))continue;
            pTree = curTree.left;
            curTree.left = curTree.right;
            curTree.right = pTree;
            stack.push(curTree.left);
            stack.push(curTree.right);
        }
    }

解法三:

  /**
     * 二叉树广度搜索
     * @param root
     */
    public static void Mirror3(TreeNode root) {
        if(root == null || (root.left == null&&root.right == null))return;
        Queue<TreeNode> queue = new LinkedList<>();
        //Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root); 
        TreeNode pTree, curTree;
        while(!queue.isEmpty()) {
            curTree = queue.poll();
            if(curTree == null || (curTree.left == null&&curTree.right == null))continue;
            pTree = curTree.left;
            curTree.left = curTree.right;
            curTree.right = pTree;
            queue.add(curTree.left);
            queue.add(curTree.right);
        }
    }

解法三我创建了一个队列 Queue queue = new ArrayDeque<>();然后提交直接报了空指针异常,看了一下源码才知道ArrayDeque中的add方法调用了addLast方法,addLast会判断一下传进来的参数是否为空,为空直接抛出空指针异常,下面为add和addLast的源码

    public boolean add(E e) {
        addLast(e);
        return true;
    }
public void addLast(E e) {
        if (e == null)
            throw new NullPointerException();
        elements[tail] = e;
        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
            doubleCapacity();
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值