본문 바로가기
알고리즘/leetcode&프로그래머스

leetCode1315. Sum of Nodes with Even-Valued Grandparent

by 윤-찬미 2021. 2. 20.

- 문제: [Sum of Nodes with Even-Valued Grandparent](https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/)

- 난이도: leetcode 기준 Medium

 

문제 해설

짝수조부모를 가진 노드의 합을 구하는 문제 였는데 Medium 치고 난이도가 높지는 않았다.

애초에 모든 노드를 checking을 했어야 해서 단순하게 BFS or DFS로 탐색을 하면 되는문제 였다. 난 DFS로 풀었다.

 

root로 들어오는 트리노드는 아래와 같이 만들어졌다.

 

**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */

그래서 단순히 node와 그 노드의 부모와 조부모를 인자로 받아 탐색했다.

탐색기준으로 아래로 노드를 한뎁스 내려가면 부모가 조부모이기 때문에 부모 node value도 받았다.

 

조부모가 짝수면 그 노드를 sum 했고 코드는 아래와 같다.

 

var sumEvenGrandparent = function(root) {
  let answer = 0;
  const check = (node, p, grandP) => {
      if (node === null) {
        return;
      }
      if (grandP && grandP%2 === 0) {
        answer += node.val;
      }
      check(node.left, node.val, p);
      check(node.right, node.val, p);
  }
  check(root, null, null);
  return answer;
 }

velog.io/@cksal5911/Sum-of-Nodes-with-Even-Valued-Grandparent

 

Sum of Nodes with Even-Valued Grandparent

문제: Sum of Nodes with Even-Valued

velog.io

위 블로그는 제가 운영 하는 블로그입니다.