Skip to content

Latest commit

 

History

History
89 lines (76 loc) · 2 KB

20201111.md

File metadata and controls

89 lines (76 loc) · 2 KB

Algorithm

103. Binary Tree Zigzag Level Order Traversal

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]
]

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 temp = stack1.pop();
                    if(temp!=null){
                        subList.add(temp.val);
                        stack2.push(temp.left);
                        stack2.push(temp.right);
                    }
                }
            }else{
                while(!stack2.isEmpty()){
                    TreeNode temp = stack2.pop();
                    if(temp!=null){
                        subList.add(temp.val);
                        stack1.push(temp.right);
                        stack1.push(temp.left);
                    }
                }
            }
            if(!subList.isEmpty()){
                listNode.add(subList);
            }
            flag++;
        }
        return listNode;
    }
}

Discuss

Review

Tip

Share