Algorithm
[리트코드] 404. Sum of Left Leaves
흰색기린
2021. 9. 9. 23:34
알고리즘 풀이 방법입니다.
문제(Problem) -> 생각(Think) -> 해결책(Solution) -> 리뷰(Review) 를 통해서 정리해서 작성합니다.
Problem📄
https://leetcode.com/problems/sum-of-left-leaves/
Sum of Left Leaves - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Think🤔
왼쪽 잎에 있는 자식이 없는 노드를 구하는 문제.
큐 사이즈를 도는 노드를 만들어주고 node.left가 비어있지 않고, 안비어있으면
그 자식의 left랑 right가 null이면 마지막 left 노드니깐 그 값을 누적해서 담아준다.
Solution✍
/**
* 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;
}
Queue<TreeNode> q = new LinkedList();
q.offer(root);
int sum=0;
while(!q.isEmpty()){
int size = q.size();
for(int i=0; i<size; i++){
TreeNode node = q.poll();
if(node.left.left == null && node.left.right == null){
sum+=node.left.val;
}
if(node.left != null){ q.offer(node.left);}
if(node.right != null){q.offer(node.right);}
}
}
return sum;
}
}
Review🤩
헬퍼를 이용하는 코드를 분석해보자.
class Solution {
int sum=0;
public int sumOfLeftLeaves(TreeNode root) {
helper(root,false);
return sum;
}
public void helper(TreeNode root,boolean isLeft)
{
if(root==null ) return;
if(root.left==null && root.right==null)
{
if(isLeft)
sum+=root.val;
}
helper(root.left,true);
helper(root.right,false);
}
}
먼저 helper를 만들어준다.
helper에는 root와 false를 파라미터 값으로 보낸다.
false는 왼쪽을 체크해준다.
다음 헬퍼를 만들고 null이면 리턴해준다.
자식이 없고 helper가 왼쪽이면 true이기 때문에 다시 넣어준다.
혼자 다시 한번 작성해보면서 다음에는 재귀적으로 짤 수 있게 노력해야겠다.