[英]count odd numbers of an N-ary tree
I am struggling with this exercise.我在这个练习中挣扎。 It tells me to count all odd numbers present in an N-Ary.
它告诉我计算 N-Ary 中存在的所有奇数。 The exercise demands me to use recursion
练习要求我使用递归
Take a look at the following tree看看下面的树
5
________|_____________
| | |
20 4 6
| _____|______
11 | | | | |
10 2 9 8 7
__|__
| |
3 1
There are 12 numbers in it.里面有12个数字。 Among these numers, 6 of them are odd which is the output i am looking for.
在这些数字中,有 6 个是奇数,这是我正在寻找的输出。 However, the code i have written doesn't solve the issue and i don't understand why.
但是,我编写的代码并没有解决问题,我不明白为什么。
The function i have implemented returns 0 which is incorrect.我实现的函数返回 0,这是不正确的。
def es7(tree):
n = 0
for element in tree.f:
n = es7(element)
if element.id % 2 == 1:
n += 1
return n
class Nodo:
def __init__(self,V):
self.id=V
self.f=[]
################### DA QUI IN GIÙ SONO SOLO FUNZIONI NECESSARIE PER I TEST #####################
def fromLista(lista):
'''Crea l'albero da una lista [valore, listafigli]
In cui lista figli contiene alberi o e' la lista vuota. '''
r=Nodo(lista[0])
r.f=[fromLista(x) for x in lista[1]]
return r
def toLista(nodo):
''' Converte l'albero in una lista di liste [valore, listafigli]'''
return [nodo.id, [toLista(x) for x in nodo.f]]
Any suggestions?有什么建议么?
Thanks谢谢
One simple approach to this problem;解决这个问题的一种简单方法; is to simply to do a level order traversal of the N-ary tree.
就是简单地对N-ary树进行级别顺序遍历。
Consider the following iterative solutions, which can give some insights into writing your recursive solution.考虑以下迭代解决方案,它们可以为编写递归解决方案提供一些见解。
To re-write your code, I would do something on these lines.要重新编写您的代码,我会在这些行上做一些事情。
Consider this snippet below:考虑下面的这个片段:
def es7(tree):
q, level = [tree], []
while any(q):
level.append([node.id for node in q])
q = [child for node in q for child in node.f if child]
ans = 0
for l in level:
for num in l:
if num & 1:
ans += num
return ans
Consider the snippet of code below: (Non-recursive Solution)考虑下面的代码片段:(非递归解决方案)
from collections import deque
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root:
return
q = deque([root])
level = 0
result = []
while q:
result.append([])
for i in range(len(q)):
node = q.popleft()
result[level].append(node.val)
for c in node.children:
q.append(c)
level += 1
return result
In the above code, result
will have all the elements of the n-ary
tree according to levels.在上面的代码中,
result
将根据级别包含n-ary
叉树的所有元素。 Parse through list, and add all the odd numbers.解析列表,并添加所有奇数。
That would be something along these lines:-那将是这样的事情:-
for level in result:
for num in result:
if num & 1:
ans += num
Alternatively you could also add-up all the odd-numbers
as you are traversing the tree.或者,您也可以在遍历树时将所有
odd-numbers
。
You are shadowing n
at each iteration.您在每次迭代时都在遮蔽
n
。 What you probably want to do is something like你可能想要做的是
def es7(tree):
n = 0
for element in tree.f:
n += es7(element) # <-- note the `+=`
if element.id % 2 == 1:
n += 1
return n
However, I think this code is still not completely sound (depending on your representation of a tree), which you might realize on a tree with a single, odd number.但是,我认为这段代码仍然不完全正确(取决于您对树的表示),您可能会在具有单个奇数的树上实现这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.