매일 조금씩

Leet code (Medium): 102. Binary Tree Level Order Traversal - Java 본문

알고리즘/Tree

Leet code (Medium): 102. Binary Tree Level Order Traversal - Java

mezo 2024. 10. 29. 22:44
728x90
반응형

 

queue를 사용해서 풀면 되는 문제였다.

 

/**
 * 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>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> output = new ArrayList<>();

        if(root == null){
            return output;
        }

        queue.offer(root);

        while(!queue.isEmpty()){
            int qsize = queue.size();
            List<Integer> level = new ArrayList<>();
            for(int i = 0; i < qsize; i++){
                TreeNode curr = queue.poll();
                level.add(curr.val);

                if(curr.left != null){
                    queue.offer(curr.left);
                }

                if(curr.right != null){
                    queue.offer(curr.right);
                }
            }
            output.add(level);
        }

        return output;
    }
}
728x90
반응형