2014-01-16 50 views
0

我的任务是构建一个函数,它返回给定二叉树中“叔叔”的数目。只有当他的兄弟(他父亲的第二个孩子)有孩子。 这是我的代码: “在二叉树中找到“叔叔” - 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,那并不重要。 有人可以帮我吗?

+0

如果你有'a = 1'后面加上'a = uncle(...)',第二行会覆盖'a'的值。 – interjay

+0

但为什么?我不会返回'a'..那么为什么'a'值正在改变? – user3045065

+0

因为您正在为其分配值。这就是'a = something'所做的。 – interjay

回答

0

我还没有测试过,但它应该可以工作。你写的代码可以减少很多。

对于初学者来说,当它不是真的需要时,你可以列为清单。

你的a和b永远不会被使用,所以没有必要给他们分配任何东西。这可能是你为什么会得到一个错误,无论你给a或b赋予什么样的价值。

然后你不需要检查a或b是否大于1.当你发现树中有另一个叔叔时,你可以增加计数。

然而,它不工作的主要原因是,每次你打电话给叔叔,你都没有通过你的新计数。这意味着它将默认值设置为None。这会导致列表重置为[0]。实际上,一个新的列表已经被创建出来,它与前一个列表不同,即使它们具有相同的名称。所以,虽然你可能认为你正在更新相同的计数,但你不是。这是一个范围问题。

def uncle(root,count=0): 
    if root.left: 
     if root.left.left or root.left.right: 
      count = uncle(root.left, count) 
      count += 1 
    if root.right: 
     if root.right.right or root.right.left: 
      count = uncle(root.right, count) 
      count += 1 
return count