LeetCode 1315. Sum of Nodes with Even-Valued Grandparent
原题链接在这里:https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/description/
题目:
Given the root
of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0
.
A grandparent of a node is the parent of its parent if it exists.
Example 1:
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.
Example 2:
Input: root = [1] Output: 0
Constraints:
- The number of nodes in the tree is in the range
[1, 104]
. 1 <= Node.val <= 100
题解:
How does a node know its grandparent, we can pass in the parent and grandparent in the dfs call.
DFS returns the sum of subtree value whose grandparent is even.
Time Complexity: O(n).
Space: O(logn). stack space.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public int sumEvenGrandparent(TreeNode root) { 18 return dfs(root, 1, 1); 19 } 20 21 private int dfs(TreeNode root, int p, int gp){ 22 if(root == null){ 23 return 0; 24 } 25 26 return (gp % 2 == 0 ? root.val : 0) + dfs(root.left, root.val, p) + dfs(root.right, root.val, p); 27 } 28 }