[LeetCode] Sum of Left Leaves

아르당·2026년 1월 9일

LeetCode

목록 보기
84/220
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

이진 트리의 루트가 주어졌을 때, 모든 왼쪽 리프 노드의 합을 반환한다.

리프 노드는 자식이 없는 노드이다. 왼쪽 리프 노드는 다른 노드의 왼쪽 자식인 리프 노드이다.

Example

#1

Input: root = [3, 9, 20, null, null, 15, 7]
Output: 24
Explanation: 이진 트리에는 왼쪽에 리프 노드가 두 개 있으며, 각각 9와 15의 값을 가지고 있다.

#2
Input: root = [1]
Output: 0

Constraints

  • 트리의 노드 수는 [1, 1000] 범위에 있다.
  • -1000 <= Node.val <= 1000

Solved

/**
 * 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 int sumOfLeftLeaves(TreeNode root) {
        if(root == null) return 0;

        int sum = 0;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        while(!q.isEmpty()){
            TreeNode curr = q.poll();

            if(curr.left != null){
                if(curr.left.left == null && curr.left.right == null){
                    sum += curr.left.val;
                }

                q.offer(curr.left);
            }

            if(curr.right != null){
                q.offer(curr.right);
            }
        }

        return sum;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글