Lachlan Jacob 5 лет назад
Родитель
Сommit
58c949aaed
3 измененных файлов: 78 добавлений и 0 удалений
  1. 55
    0
      problems/1315/main.py
  2. 20
    0
      problems/1315/problem.txt
  3. 3
    0
      problems/1315/run.sh

+ 55
- 0
problems/1315/main.py Просмотреть файл

@@ -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))

+ 20
- 0
problems/1315/problem.txt Просмотреть файл

@@ -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.


+ 3
- 0
problems/1315/run.sh Просмотреть файл

@@ -0,0 +1,3 @@
#!/bin/bash

python3 main.py

Загрузка…
Отмена
Сохранить