Sum of Nodes with Even-Valued Grandparent
Sum of Nodes with Even-Valued Grandparent
- 문제: 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;
};
Author And Source
이 문제에 관하여(Sum of Nodes with Even-Valued Grandparent), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@cksal5911/Sum-of-Nodes-with-Even-Valued-Grandparent저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)