Zigzag sequence traversal of binary tree java

Given a binary tree, return the zigzag hierarchy traversal of its node values. (That is, traverse the next layer from left to right, and then from right to left, and so on, alternating between layers).

For example:
Given a binary tree [3,9,20,null,null,15,7],

3
/ \
9 20
…/ \
…15 7
Return the zigzag sequence traversal as follows:

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

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Idea: bfs question, whether to deal with left to right or right to left is fine

/**
 * 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) {
    
    
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        if (root == null) {
    
    return res;}
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        //offer和put的区别,队列满offer返回false,put抛出异常
        queue.offer(root);
        boolean isOrderLeft = true;

        while (!queue.isEmpty()) {
    
    
            Deque<Integer> levelList = new LinkedList<Integer>();
            int size = queue.size();
            for (int i = 0; i < size; ++i) {
    
    
                TreeNode curNode = queue.poll();
                if (isOrderLeft) {
    
    
                    levelList.offerLast(curNode.val);
                } else {
    
    
                    levelList.offerFirst(curNode.val);
                }
                if (curNode.left != null) {
    
    
                    queue.offer(curNode.left);
                }
                if (curNode.right != null) {
    
    
                    queue.offer(curNode.right);
                }
            }
            res.add(new LinkedList<Integer>(levelList));
            
            isOrderLeft = !isOrderLeft;
        }

        return res;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43824233/article/details/111554559