[The sword refers to the offer brushing the question] AcWing 45. Zigzag printing binary tree (simulation, application of stack)

ideas

Hierarchical traversal

At the end of each layer, add a null to the queue

Zigzag printing

Invert the result in level every time you switch layers

topic

Please implement a function to print the binary tree from top to bottom in zigzag order.

That is, the first line is printed from left to right, the second layer is printed from right to left, the third line is printed from left to right, and so on.
data range

The number of nodes in the tree [0,1000]

.
Sample

Input binary tree as shown below [8, 12, 2, null, null, 6, 4, null, null, null, null]
8
/
12 2
/
6 4
Output: [[8], [2, 12], [ 6, 4]]

code

/**
 * 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>> printFromTopToBottom(TreeNode root) {
    
    
        boolean flag = false;
        
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null) return res;
        
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        q.offer(null);
        
        List<Integer> level = new ArrayList<Integer>();
        while (q.size() > 0) {
    
    
            TreeNode t = q.poll();
            if (t == null)
            {
    
    
                if (level.size() == 0) break;
                if (flag) Collections.reverse(level);
                res.add(new ArrayList<Integer>(level));
                level.clear();
                q.offer(null);
                
                // 取反操作必须在 #26 行之后
                flag = !flag;  // 取反操作
                continue;
            }
            
            level.add(t.val);
            if (t.left != null)
                q.offer(t.left);
            if (t.right != null)
                q.offer(t.right);
        }
        return res;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326170982&siteId=291194637