LeetCode-Binary Tree Zigzag Level Order Traversal

Keywords: IE Java

Description:
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,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

Given a binary tree, it is required to output z-type sequence traversal.

Solution: for hierarchical traversal, we can think of using queue to achieve; then, for the z-type hierarchical traversal required by the topic, we need an additional variable to record the traversal direction in each layer; we use linked list to store the nodes of each layer, so that when the traversal of the layer is from left to right, we insert elements to the end of the linked list; when the traversal of the layer is from From right to left, we insert elements into the head of the list.

Java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        ArrayList<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.addLast(root);
        int len = 1;
        int direction = 1;
        while (!queue.isEmpty()) {
            LinkedList<Integer> list = new LinkedList<>();
            int temp = len;
            len = 0;
            while (temp-- > 0) {
                TreeNode node = queue.poll();
                if (direction == 1) {
                    list.addLast(node.val);
                } else {
                    list.addFirst(node.val);
                }
                if (node.left != null) {
                    queue.addLast(node.left);
                    len++;
                }
                if (node.right != null) {
                    queue.addLast(node.right);
                    len++;
                }
            }
            result.add(list);
            direction *= -1;
        }

        return result;
    }
}

Posted by hyd_guy on Fri, 18 Oct 2019 10:38:09 -0700