1. 문제
Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.)
If there are no nodes with an even-valued grandparent, return 0.
2. 예시
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
3. 풀이
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumEvenGrandparent = function(root) {
let result = 0;
let trav = function(node, pa, gpa) {
if(!node) return;
if(gpa && gpa%2 === 0){
result += node.val;
}
gpa = pa;
pa = node.val;
trav(node.left, pa, gpa);
trav(node.right, pa, gpa);
};
trav(root, null, null);
return result;
};
4. 결과
14 / 14 test cases passed.
Status: Accepted
Runtime: 84 ms
Memory Usage: 42.8 MB
반응형
'Programming' 카테고리의 다른 글
[LeetCode] [Easy] [JS] 53. Maximum Subarray (0) | 2020.04.04 |
---|---|
[DynamicProgramming] Kadane's Algorithm(카데인 알고리즘) (0) | 2020.04.04 |
[LeetCode] [Easy] [JS] 1108. Defanging an IP Address (0) | 2020.04.03 |
[Python] 파이썬이 미래의 프로그래밍 언어가 아닌 이유 (0) | 2020.04.03 |
[GraphQL] GraphQL이란 - 2. GraphQL의 구조 (0) | 2020.03.26 |