我的任务是构建一个函数,它返回给定二叉树中“叔叔”的数目。只有当他的兄弟(他父亲的第二个孩子)有孩子。 这是我的代码: “在二叉树中找到“叔叔” - Python
def uncle(root,count = None):
if count is None:
count = [0]
a,b = 0,0
if root.left:
if root.left.left or root.left.right:
a = uncle(root.left)
a = 1
if root.right:
if root.right.right or root.right.left:
b = uncle(root.right)
b = 1
if b > 0:
count[0] += 1
if a > 0:
count[0] += 1
return count[0]
” 这是bin_tree类: “
Class bin_tree():
def __init__(self,data, left_child = None, right_child = None):
self.data = data
self.left = left_child
self.right = right_child
” 我的问题是这样的: 当我换行: A =叔叔(root.left) a = 1 它没有工作(含义=变量a由于某种原因已将其值更改为0),我绝对不知道为什么......我认为它应该起作用,因为 如果我首先调用函数的递归或首先说a = 1,那并不重要。 有人可以帮我吗?
如果你有'a = 1'后面加上'a = uncle(...)',第二行会覆盖'a'的值。 – interjay
但为什么?我不会返回'a'..那么为什么'a'值正在改变? – user3045065
因为您正在为其分配值。这就是'a = something'所做的。 – interjay