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

给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.*;

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>(0);
        }

        LinkedList<TreeNode> queue = new LinkedList<>();

        List<List<Integer>> ret = new ArrayList<>();
        int deep = 0;

        TreeNode curEnd = root, nextEnd = null;

        queue.offerLast(root);

        while (!queue.isEmpty()) {
            TreeNode cur;
            if (deep % 2 == 0) {
                cur = queue.pollFirst();
            } else {
                cur = queue.pollLast();
            }

            List<Integer> item;

            if (ret.size() == deep) {
                item = new ArrayList<>();
                ret.add(item);
            } else {
                item = ret.get(deep);
            }

            item.add(cur.val);

            if (deep % 2 == 0) {
                if (cur.left != null) {
                    nextEnd = nextEnd == null ? cur.left : nextEnd;
                    queue.offerLast(cur.left);
                }
                if (cur.right != null) {
                    nextEnd = nextEnd == null ? cur.right : nextEnd;
                    queue.offerLast(cur.right);
                }
            } else {
                if (cur.right != null) {
                    nextEnd = nextEnd == null ? cur.right : nextEnd;
                    queue.offerFirst(cur.right);
                }
                if (cur.left != null) {
                    nextEnd = nextEnd == null ? cur.left : nextEnd;
                    queue.offerFirst(cur.left);
                }
            }

            if (cur == curEnd) {
                deep++;
                curEnd = nextEnd;
                nextEnd = null;
            }
        }

        return ret;
    }
}


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;
    }
}
posted @ 2021-12-07 00:13  Tianyiya  阅读(31)  评论(0)    收藏  举报