@@ -0,0 +1,55 @@ | |||
# Definition for a binary tree node. | |||
class TreeNode: | |||
def __init__(self, x): | |||
self.val = x | |||
self.left = None | |||
self.right = None | |||
class Solution: | |||
def sumEvenGrandparent(self, root): | |||
if root is None: | |||
return 0 | |||
return self.sumEG(root, False, False) | |||
def sumEG(self, tree, grandParentEven, parentEven): | |||
sum = 0 | |||
if tree is None: | |||
return sum | |||
if grandParentEven: | |||
sum += tree.val | |||
sum += self.sumEG(tree.left, parentEven, tree.val % 2 == 0) | |||
sum += self.sumEG(tree.right, parentEven, tree.val % 2 == 0) | |||
return sum | |||
s = Solution() | |||
print("Expected: 18") | |||
tree = TreeNode(6) | |||
a = TreeNode(7) | |||
b = TreeNode(2) | |||
c = TreeNode(7) | |||
d = TreeNode(8) | |||
e = TreeNode(9) | |||
f = TreeNode(1) | |||
g = TreeNode(4) | |||
h = TreeNode(1) | |||
i = TreeNode(3) | |||
j = TreeNode(5) | |||
i.right = j | |||
d.right = i | |||
d.left = h | |||
tree.right = d | |||
c.right = g | |||
c.left = f | |||
a.right = c | |||
b.left = e | |||
a.left = b | |||
tree.left = a | |||
print("Got:", s.sumEvenGrandparent(tree)) | |||
@@ -0,0 +1,20 @@ | |||
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. | |||
(There is an example picture here, to get an idea of the tree check out the code. | |||
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. | |||
Constraints: | |||
The number of nodes in the tree is between 1 and 10^4. | |||
The value of nodes is between 1 and 100. | |||
@@ -0,0 +1,3 @@ | |||
#!/bin/bash | |||
python3 main.py |