0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode 103. Binary Tree Zigzag Level Order Traversal

Posted at

アプローチ

BFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    if(root == null) return new ArrayList<>();
        
        List<List<Integer>> list= new ArrayList<>();

        Queue<TreeNode> q= new LinkedList<>();

        q.offer(root);

        boolean isReversed=true;
        while(!q.isEmpty()){
            int size= q.size();
            ArrayList<Integer> innerList= new ArrayList<>();
            for(int i=0; i<size; i++){
                TreeNode current= q.poll();
                if(current.left != null) q.offer(current.left);
                if(current.right != null) q.offer(current.right);
                innerList.add(current.val);                
            }
            if(!isReversed){
                Collections.reverse(innerList);
            }

            list.add(innerList);
            isReversed= !isReversed;

        }
        return list;
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?