Given the root of a binary tree, return the sum of values of nodes with aneven-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.
flowchart TD
%% styles
classDef gp fill:#cfe9ff,stroke:#2b6fb3,stroke-width:1px;
classDef counted fill:#ffd2d2,stroke:#b33b3b,stroke-width:1px;
classDef normal fill:#fff,stroke:#333,stroke-width:1px;
classDef hidden display:none;
A("6"):::gp
A --- B("7"):::normal & C("8"):::gp
B --- D("2"):::counted & E("7"):::counted
C --- F("1"):::counted & G("3"):::counted
D --- H("9"):::normal
D ~~~ N1:::hidden
E --- I("1"):::normal & J("4"):::normal
G ~~~ N2:::hidden
G --- K("5"):::counted
1
2
3
Input: root =[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]Output: 18Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
We use DFS or BFS to traverse the tree, passing down the parent and grandparent values. If the grandparent is even, add the current node’s value to the running result res.
structTreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
classSolution {
public:int sumEvenGrandparent(TreeNode* root, int p =1, int gp =1) {
if (!root) return0;
int res = (gp %2==0) ? root->val : 0;
res += sumEvenGrandparent(root->left, root->val, p);
res += sumEvenGrandparent(root->right, root->val, p);
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classTreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}
classSolution {
publicintsumEvenGrandparent(TreeNode root) {
return dfs(root, 1, 1);
}
privateintdfs(TreeNode node, int parent, int grandparent) {
if (node ==null) return 0;
int res = (grandparent % 2 == 0) ? node.val : 0;
res += dfs(node.left, node.val, parent);
res += dfs(node.right, node.val, parent);
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classTreeNode(var `val`: Int) {
var left: TreeNode? = nullvar right: TreeNode? = null}
classSolution {
funsumEvenGrandparent(root: TreeNode?): Int {
fundfs(node: TreeNode?, parent: Int, grandparent: Int): Int {
if (node ==null) return0var res = if (grandparent % 2==0) node.`val` else0 res += dfs(node.left, node.`val`, parent)
res += dfs(node.right, node.`val`, parent)
return res
}
return dfs(root, 1, 1)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Definition for a binary tree node.classTreeNode:
def__init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
classSolution:
defsumEvenGrandparent(self, root: TreeNode) -> int:
defdfs(node, parent, grandparent):
ifnot node:
return0 res = node.val if grandparent %2==0else0 res += dfs(node.left, node.val, parent)
res += dfs(node.right, node.val, parent)
return res
return dfs(root, 1, 1)