[LeetCode-Graph] Sum of Nodes with Even-Valued Grandparent

CHOI YUN HO·2022년 1월 14일
0

알고리즘 문제풀이

목록 보기
63/63

📃 문제 설명

Sum of Nodes with Even-Valued Grandparent

[문제 출처 : LeetCode]

👨‍💻 해결 방법

짝수조부모를 가진 노드의 합을 구하는 문제.

애초에 모든 노드를 탐색해야 해서
DFS나 BFS로 풀면 되는 문제였다.

난 DFS로 풀었음

👨‍💻 소스 코드

package Leetcode.DFSBFS.Medium;

public class SumEvenGrandparent {
    int sum = 0;
    public void dfs(TreeNode node, TreeNode parent, TreeNode grandParent) {
        if (grandParent != null && (grandParent.val % 2) != 0){
            sum += node.val;
        }
        if (node.right != null) {
            dfs(node.right, node, parent);
        }
        if (node.left != null) {
            dfs(node.left, node, parent);
        }
    }

    public int solution(TreeNode root) {
        dfs(root, null, null);

        return sum;
    }

    public static void main(String[] args) {
        SumEvenGrandparent seg = new SumEvenGrandparent();
        TreeNode root = new TreeNode();
        seg.solution(root);
    }
} 
profile
가재같은 사람

0개의 댓글