1

I have created a Tree structure that is not a binary tree and having difficulties in getting the correct node count.

class TreeNode(object):
  def __init__(self, name='root', children=None,Parent=[]):
    self.Name = name
    self.Parents=Parent

    self.Children = []
    if children is not None:
        for child in children:
            self.add_child(child.Name)

 def __repr__(self):
   return self.Name

 def add_child(self, node):    
  self.Children.append(node)

and this is the latest in what I have tried to do in order to count the number of nodes in the tree.

def countNodes(Tree):      

   for Child in Tree.Children:
      return countNodes(Child)+1

   return 1

Could someone explain why this doesn't work? EDIT: I should clarify, When I say doesn't work it gives me a completely wrong count for he number of nodes in my graph.

Belrouk
  • 115
  • 1
  • 2
  • 10

2 Answers2

1

You countNodes function is not well. A parent node can have two childs, if you put a return statement within the for loop, it will return on the first child count and the second child count will be missing. You need to do something like this:

def countNodes(Tree):      
   count = 1
   for Child in Tree.Children:
      count +=  countNodes(Child)
   return count
levi
  • 22,001
  • 7
  • 73
  • 74
0

Just to add @levi has missed an edge case where root is None

so the modified code will be :

def numNodes(root):
    if root == None:
        return 0 
    node = 1
    for child in root.children:
        node = node + numNodes(child)
    return node