简体   繁体   中英

Counting nodes in a binary tree recursively

I have to count nodes in a binary tree recursively. I'm new to python and can't find any solution for my problem to finish my code.

This is what I have already tried. As you can see it is not complete, and I can't figure out where to go.

class Tree:
    def __init__(self, root):
        self.root = root

    def add(self, subtree):
        self.root.children.append(subtree)

class Node:
    def __init__(self, value, children=None):
        self.value = value
        self.children = children if children is not None else []

def check_root(tree):
    if tree.root is None:
        return 0
    if tree.root is not None:
        return count_nodes(tree)

def count_nodes(tree):
    if tree.root.children is not None:
        j = 0
        for i in tree.root.children:
            j = 1 + count_nodes(tree)
        return j


print(count_nodes(Tree(None))) # 0
print(count_nodes(Tree(Node(10)))) # 1
print(count_nodes(Tree(Node(5, [Node(6), Node(17)])))) #3

With every new step I'm getting different error. Eg with this code I have exceeded maximum recursion depth.

Thank you for your time reading this. Any hint or help what to do next would be greatly appreciated.

I would start by passing the root node to the count_nodes function -

print(count_nodes(Tree(None)).root) # 0
print(count_nodes(Tree(Node(10))).root) # 1
print(count_nodes(Tree(Node(5, [Node(6), Node(17)]))).root) #3

or make a helper function for that.

Then the count_nodes function can simply look like this

def count_nodes(node):
    return 1 + sum(count_nodes(child) for child in node.children)

EDIT: I have just noticed, you can have a None root, this means, you should also handle that:

def count_nodes(node):
    if node is None:
        return 0
    return 1 + sum(count_nodes(child) for child in node.children)

And if you really want to handle tree or node in one function, you can make it a bit uglier:

def count_nodes(tree_or_node):
    if isinstance(tree_or_node, Tree):
        return count_nodes(tree_or_node.root)
    if tree_or_node is None:
        return 0
    return 1 + sum(count_nodes(child) for child in tree_or_node.children)

and then you can call it like you originally did.

Your problem is that you're counting the same tree infinitely. Take a look at this line:

j = 1 + count_nodes(tree)

An Easy Way:

Lets assume, A is a binary tree with children or nodes which are not NULL . eg

     3  
    / \  
  7     5  
   \     \  
   6       9  
  / \     /  
 1  11   4 

Now in order to count number of nodes, we have a simple workaround.

Recursive Method: >>> get_count(root)

For a binary tree, the basic idea of Recursion is to traverse the tree in Post-Order . Here, if the current node is full, we increment result by 1 and add returned values of the left and right sub-trees such as:

class TestNode(): 


def __init__(self, data):  
    self.data = data 
    self.left = None
    self.right = None

Now we move forward to get the count of full nodes in binary tree by using the method below:

def get_count(root): 

  if (root == None): 
    return 0

  res = 0
  if (root.left and root.right): 
     res += 1

  res += (get_count(root.left) + 
        get_count(root.right))  
  return res  

At the end, in order to run the code, we'll manage a main scope : Here we create our binary tree A as given above:

if __name__ == '__main__': 

  root = TestNode(3)  
  root.left = TestNode(7)  
  root.right = TestNode(5)  
  root.left.right = TestNode(6)  
  root.left.right.left = TestNode(1)  
  root.left.right.right = TestNode(4)

Now at the end, inside main scope we will print count of binary tree nodes such as:

  print(get_Count(root)) 

Here is the time complexity of this recursive function to get_count for binary tree A .

Time Complexity: O(n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM