#leetcode#Binary Tree Zigzag Level Order Traversal

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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

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

这题可以判断行的奇数偶数来判断从左往右或从右往左,用两个stack, 我的思路是仍然用queue来做level order traversal,如果是奇数行(第一行level为0),则在原来基础上把所有的TreeNode先放到一个stack中,再pop out,依次放入ArrayList中,


/**
 * 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>> res = new ArrayList<List<Integer>>();
        if(root == null)    
            return res;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int flag = 1;
        while(!queue.isEmpty()){
            flag *= -1;
            int size = queue.size();
            List<Integer> item = new ArrayList<>();
            LinkedList<TreeNode> stack = new LinkedList<>();
            
            for(int i = 0; i < size; i++){
                TreeNode cur = queue.poll();
                if(flag == -1){
                    item.add(cur.val);
                }
                if(flag == 1){
                    stack.push(cur);
                }
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
            
            if(flag == 1){
                while(!stack.isEmpty()){
                    item.add(stack.pop().val);
                }
            }
            
            res.add(item);
        }
        
        return res;
    }
}




你可能感兴趣的:(LeetCode)