Monday, March 13, 2017

Leetcode -- 103. Binary Tree Zigzag Level Order Traversal (BFS)

103. Binary Tree Zigzag Level Order Traversal (BFS)
medium
https://leetcode.com/problems/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]
]
思路: just like level order traversal, but we travel the tree in Z shape.
          So any even row, the order of nodes in the row will be reversed when adding to the result arraylist: Collections.reverse(res.get(level))

Complexity: Time O(n) Space O(n)

public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) return res;
        Queue<TreeNode> q = new LinkedList();
        int level = 0;
        q.offer(root);
        while(!q.isEmpty()){
            int size = q.size();
            res.add(new ArrayList());
            for(int i = 0; i < size; i++){
                TreeNode cur = q.poll();
                res.get(level).add(cur.val);
                if(cur.left != null){
                    q.offer(cur.left);
                }
                if(cur.right != null){
                    q.offer(cur.right);
                }
            }
            if(level%2 == 1)
                Collections.reverse(res.get(level));
            level++;
        }
        return res;
    }



No comments:

Post a Comment