• Symmetric Tree 之 ArrayDeque,LinkedList 使用区别


    本人写代码,无论是用到栈结构,队列结构,都习惯用deque,因为deque支持在头部和尾部插入或删除元素。

    但deque有 ArrayDeque 和 LinkedList 两种框架。

    主要区别在于LinkedList支持插入null元素

    这在下面这道leetcode题Symmetric Tree得以运用。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isSymmetric(TreeNode root) {
            Deque<TreeNode> queue = new LinkedList<>();//允许插入null
            queue.addLast(root);
            queue.addLast(root);
            while(!queue.isEmpty()){
                TreeNode t1 = queue.removeFirst();
                TreeNode t2 = queue.removeFirst();
                if(t1 == null && t2 == null) continue;
                if(t1 == null || t2 == null) return false;
                if(t1.val != t2.val) return false;
                queue.addLast(t1.left);//可能为null
                queue.addLast(t2.right);
                queue.addLast(t1.right);
                queue.addLast(t2.left);
            }
            return true;
        }
    }

    ArrayDeque基于 循环数组 实现

    LinkedList基于 双向链表 实现

    PriorityQueue基于 最小堆(完全二叉树) 实现

    ArrayDeque:双端队列,线程不安全,性能高于LinkedList,不允许插入null元素

    LinkedList:双端队列,线程不安全,首尾元素操作效率高,低效随机访问

    PriorityQueue:线程不安全,不允许插入null元素,动态数组实现最小堆,remove方法一直返回最小元素

  • 相关阅读:
    ZOJ 1403 解密
    HDU 1021 斐波那契
    Wannafly挑战赛26题解
    NOI2019省选模拟赛 第三场
    NOI2019省选模拟赛 第五场
    洛谷P5280 [ZJOI2019]线段树(线段树)
    NOI2019省选模拟赛 第六场
    Wannafly挑战赛29题解
    李超线段树学习笔记
    洛谷P4069 [SDOI2016]游戏(李超线段树)
  • 原文地址:https://www.cnblogs.com/yawenw/p/12881592.html
Copyright © 2020-2023  润新知