Java BFS solution reuse level order traversal


  • 0
    S

    The idea is to reuse the code for level order traversal and switch the insertion order in the inner linked list on every iteration from front to rear.

    /**
     * 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>> result = new ArrayList();
            if(root == null) return result;
            LinkedList<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            boolean flip = true;
            while(queue.size() > 0) {
                LinkedList<Integer> list = new LinkedList();
                int size = queue.size();
                for(int i=0; i<size; i++) {
                    TreeNode element = queue.remove();
                    if(flip) list.add(element.val);
                    else list.addFirst(element.val);
                    if(element.left != null) queue.add(element.left);
                    if(element.right != null) queue.add(element.right);
                }
                result.add(list);
                flip = !flip;
            }
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.