JAVA: Add a boolean variable isOdd, basic on Binary Tree Level Order Traversal


  • 0
    G

    I add a boolean variable isOdd, basic on Binary Tree Level Order Traversal.
    If isOdd is true, no change, else addFirst. Done!

    public class Solution {
    	public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    		List<List<Integer>> lists = new ArrayList<>();
    		if (root == null) {
    			return lists;
    		}
    		Queue<TreeNode> queue = new LinkedList<>();
    		queue.offer(root);
    		boolean isOdd = true;
    		while (!queue.isEmpty()) {
    			LinkedList<Integer> list = new LinkedList<>();
    			int size = queue.size();
    			while (size-- > 0) {
    				TreeNode node = queue.poll();
    				if (isOdd) {
    					list.add(node.val);
    				} else {
    					list.addFirst(node.val);
    				}
    				if (node.left != null) {
    					queue.add(node.left);
    				}
    				if (node.right != null) {
    					queue.add(node.right);
    				}
    
    			}
    			isOdd = !isOdd;
    			lists.add(list);
    		}
    		return lists;
    	}
    }
    

Log in to reply
 

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