Niuke Net Brush Questions-Zigzag Hierarchical Traversal of Binary Trees

Problem Description

Given a binary tree, return the zigzag layer sequence traversal of the binary tree, (the first layer is from left to right, and the next layer is from right to left, alternating like this)

Enter description:
Enter a tree

Output description:
Zigzag traversal of the output tree

Example

Example 1

Enter
{3,9,20,#,#,15,7}

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

Solutions

analysis

  1. The local area is obviously a breadth-first search (bfs) topic. The breadth-first search generally uses the data structure of the queue to traverse the nodes of each layer, and then add the left node and the right node in turn, and use the flag to determine whether the result needs to be done. Reverse.

method

  1. Breadth first search

Code

// 思路1
public class Solution {
    
      
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
    
    
        if (root == null) return new ArrayList<>();
        // write code here
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        boolean flag = true;
        while (!queue.isEmpty()) {
    
    
            ArrayList<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
    
    
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            if (!flag) {
    
    
                Collections.reverse(list);
            }
            flag = !flag;
            result.add(list);
        }

        return result;
    }
}

Time complexity analysis:
O(M): Breadth first search needs to traverse all nodes.

Space complexity analysis:
O(1): In addition to the results, no additional storage space is used.

If you want to test, you can go directly to the link of Niuke.com to do the test

Zigzag sequence traversal of binary tree

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/113768701