Jan 27 - Binary Tree Zigzag Level Order Traversal; BST; Queue and Stack;

As we know, if we traverse in from left to right level order, we can use a Queue to store all the nodes in this level from left to right. While in zigzag, Stack is prefered in this case. The only thing we should be careful is that when should we push the left child first, when should we push the right child node first. Here we can set a boolean variable to control this push order.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> resultList = new ArrayList<>();
        if(root == null) return resultList;
        Stack<TreeNode> nodes = new Stack<>();
        nodes.push(root);
        boolean flag = true;
        //int i = 1;
        while(!nodes.isEmpty()){
            //int count = 0;
            Stack<TreeNode> nextLevel = new Stack<>();
            List<Integer> list = new ArrayList<>();
            if(!flag){
                while(!nodes.isEmpty()){
                    TreeNode node = nodes.pop();
                    list.add(node.val);
                    if(node.right != null) nextLevel.push(node.right);
                    if(node.left != null) nextLevel.push(node.left);
                }
                flag = true;
            }
            else{
                while(!nodes.isEmpty()){
                    TreeNode node = nodes.pop();
                    list.add(node.val);
                    if(node.left != null) nextLevel.push(node.left);
                    if(node.right != null) nextLevel.push(node.right);
                }
                flag = false;
            }
            resultList.add(list);
            nodes = nextLevel;
        }
        return resultList;
    }
}

 

你可能感兴趣的:(Jan 27 - Binary Tree Zigzag Level Order Traversal; BST; Queue and Stack;)