Skip to content

Files

Latest commit

Jul 22, 2021
c401260 · Jul 22, 2021

History

History
99 lines (78 loc) · 2.15 KB

20210722.md

File metadata and controls

99 lines (78 loc) · 2.15 KB

Algorithm

103. Binary Tree Zigzag Level Order Traversal

Description

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]

Example 2:

Input: root = [1]
Output: [[1]]

Example 3:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100

Solution

/**
 * 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>> listNode = new LinkedList<>();
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        if(root == null){
            return listNode;
        }
        int flag = 0;
        stack1.push(root);
        while(!stack1.isEmpty()||!stack2.isEmpty()){
            List<Integer> subList = new LinkedList<>();
            if(flag%2==0){
                while(!stack1.isEmpty()){
                    TreeNode node = stack1.pop();
                    if(node!=null){
                        subList.add(node.val);
                        stack2.push(node.left);
                        stack2.push(node.right);
                    }
                }
            }else{
                while(!stack2.isEmpty()){
                    TreeNode node = stack2.pop();
                    if(node!=null){
                        subList.add(node.val);
                        stack1.push(node.right);
                        stack1.push(node.left);
                    }
                }
            }
            if(!subList.isEmpty()){
                listNode.add(subList);
            }
            flag++;
        }
        return listNode;
    }
}

Discuss

Review

Tip

Share