LeetCode每日一题:锯齿形输出二叉树的层序遍历

问题描述

Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree{3,9,20,¥,¥,15,7},
3
/
9 20
/
15 7

return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]

confused what”{1,¥,2,3}”means? > read more on how binary tree is serialized on OJ.

OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘¥’ signifies a path terminator where no node exists below.
Here’s an example:
1
/
2 3
/
4

5
The above binary tree is serialized as”{1,2,3,¥,¥,4,¥,¥,5}”.

问题分析

这题主要还是考层序遍历,但是每层可能正序输出和倒序输出,所以我们最好用栈或者最后倒序一下输出

代码实现

public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.isEmpty() == false) {
            ArrayList<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.poll();
                list.add(curNode.val);
                if (curNode.left != null) queue.offer(curNode.left);
                if (curNode.right != null) queue.offer(curNode.right);
            }
            result.add(list);
        }
        //处理锯齿形的输出
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        int count = 0;
        while (count < result.size()) {
            //一行正输出,一行反输出
            ArrayList<Integer> list = new ArrayList<>();
            if (count % 2 == 0) {
                for (int i = 0; i < result.get(count).size(); i++) {
                    list.add(result.get(count).get(i));
                }
            } else if (count % 2 == 1) {
                for (int i = 0; i < result.get(count).size(); i++) {
                    list.add(0, result.get(count).get(i));
                }
            }
            count++;
            res.add(list);
        }
        return res;
    }
    原文作者:二叉树
    原文地址: https://www.jianshu.com/p/2ac02b1b3ae4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞