103. 二叉树的锯齿形层序遍历 + 双端队列 + 栈 + 层序遍历

103. 二叉树的锯齿形层序遍历

LeetCode_103

相似题型:剑指 Offer 32 - III. 从上到下打印二叉树 III

题目描述

LinkedList(Deque的一个实现类)的用法

增加:
add(E e):在链表后添加一个元素;   通用方法
addFirst(E e):在链表头部插入一个元素;  特有方法
addLast(E e):在链表尾部添加一个元素;  特有方法
push(E e):与addFirst方法一致
add(int index, E element):在指定位置插入一个元素。 
offer(E e):在链表尾部插入一个元素
offerFirst(E e):JDK1.6版本之后,在头部添加; 特有方法                                                                                                        
offerLast(E e):JDK1.6版本之后,在尾部添加; 特有方法
删除:
**remove() :移除链表中第一个元素;    通用方法  **
remove(E e):移除指定元素;   通用方法
removeFirst(E e):删除头,获取元素并删除;  特有方法
removeLast(E e):删除尾;  特有方法
==pop():和removeFirst方法一致,删除头。 ==
poll():查询并移除第一个元素     特有方法
pollFirst():删除头;  特有方法
pollLast():删除尾;  特有方法
查:
get(int index):按照下标获取元素;  通用方法
getFirst():获取第一个元素;  特有方法
getLast():获取最后一个元素; 特有方法
peek():获取第一个元素,但是不移除;  特有方法
peekFirst():获取第一个元素,但是不移除; 
peekLast():获取最后一个元素,但是不移除;
pollFirst():查询并删除头;  特有方法
pollLast():删除尾;  特有方法
poll():查询并移除第一个元素     特有方法

java代码实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if(root == null)
            return new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        Deque<TreeNode> que = new LinkedList<>();
        que.push(root);
        boolean isOdd = true;//是否是奇数
        while(!que.isEmpty()){
            List<Integer> list = new ArrayList<>();//用来存储当前层的所有节点
            Deque<TreeNode> sta = new LinkedList<>();//用来存储下一层的结点
            for(int i = que.size(); i>0; i--){//循环遍历当前层
                TreeNode now = que.pop();
                list.add(now.val);
                if(isOdd){//如果当前是奇数层,下一层进栈的顺序是从左到右
                    if(now.left != null)
                        sta.push(now.left);
                    if(now.right != null)
                        sta.push(now.right);
                }else{
                    if(now.right != null)
                        sta.push(now.right);
                    if(now.left != null)
                        sta.push(now.left);
                }
            }
            while(!sta.isEmpty()){
                que.add(sta.pop());//这里不能用push,push是addFirst的含义
            }
            result.add(list);//将当前层的结点加入到结果列表中
            isOdd = !isOdd;
        }
        return result;
    }
}
posted @ 2021-03-08 19:57  Garrett_Wale  阅读(89)  评论(0编辑  收藏  举报