当前位置: 首页 > 图灵资讯 > 技术篇> #yyds干货盘点# LeetCode程序员面试金典:二叉树的锯齿形层序遍历

#yyds干货盘点# LeetCode程序员面试金典:二叉树的锯齿形层序遍历

来源:图灵教育
时间:2023-05-15 09:33:39

题目:

给你二叉树的根节点 root ,返回其节点值 锯齿形层序遍历 。(即从左到右,再从右到左进行下一层遍历,以此类推,层与层交替进行)。

示例 1:

输入:root = [3,9,20,null,null,15,7]

输出:[[3],[20,9],[15,7]

示例 2:

输入:root = [1]

输出:[[1]]

示例 3:

输入:root = []

输出:[]

代码实现:

class Solution {    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {        List<List<Integer>> ans = new LinkedList<List<Integer>>();        if (root == null) {            return ans;        }        Queue<TreeNode> nodeQueue = new ArrayDeque<TreeNode>();        nodeQueue.offer(root);        boolean isOrderLeft = true;        while (!nodeQueue.isEmpty()) {            Deque<Integer> levelList = new LinkedList<Integer>();            int size = nodeQueue.size();            for (int i = 0; i < size; ++i) {                TreeNode curNode = nodeQueue.poll();                if (isOrderLeft) {                    levelList.offerLast(curNode.val);                } else {                    levelList.offerFirst(curNode.val);                }                if (curNode.left != null) {                    nodeQueue.offer(curNode.left);                }                if (curNode.right != null) {                    nodeQueue.offer(curNode.right);                }            }            ans.add(new LinkedList<Integer>(levelList));            isOrderLeft = !isOrderLeft;        }        return ans;    }}