Given a Binary tree, count total number of non-leaf nodes in the tree
Input : Output :2 Explanation In the above tree only two nodes 1 and 2 are non-leaf nodes
We recursively traverse the given tree. While traversing, we count non-leaf nodes in left and right subtrees and add 1 to the result.
# Python3 program to count total number
# of non-leaf nodes in a binary tree
# class that allocates a new node with the
#given data and None left and right pointers.
self.data = data
self.left = self.right = None
# Computes the number of non-leaf
# nodes in a tree.
# Base cases.
if (root == None or (root.left == None and
root.right == None)):
# If root is Not None and its one of
# its child is also not None
return (1 + countNonleaf(root.left) +
# Driver Code
if __name__ == ‘__main__’:
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
# This code is contributed by PranchalK