Posted on by Kalkicode
Code Binary Tree

Count complete even nodes path of binary tree in python

All even nodes path from root to leaf in binary tree

Python program for Count complete even nodes path of binary tree. Here mentioned other language solution.

#  Python 3 program for
#  Count even node paths in Binary Tree

#  Binary Tree node
class TreeNode :
    def __init__(self, data) :
        #  Set node value
        self.data = data
        self.left = None
        self.right = None
class BinaryTree :
    def __init__(self) :
        #  Set initial tree root
        self.root = None
    #  Count all paths from root to leaf
    #  which containing all Even nodes
    def  countEvenNodePath(self, node) :
        if (node == None or node.data % 2 != 0) :
            #  When tree node is null or
            #  its contain Odd value.
            return  0
        else :
            if (node.left == None and node.right == None) :
                #  When get leaf node
                return  1
            return  self.countEvenNodePath(node.left) + \
              self.countEvenNodePath(node.right)
def main() :
    #  New binary tree
    tree = BinaryTree()
    #  Construct Binary Tree
    #  -----------------------
    #          2
    #         / \
    #        /   \ 
    #       /     \
    #      4       10
    #     / \      / \
    #    8   1    12  6
    #   / \      /  \  \
    #  10  30   7    4  8
    #  Add tree node
    tree.root = TreeNode(2)
    tree.root.left = TreeNode(4)
    tree.root.right = TreeNode(10)
    tree.root.right.right = TreeNode(6)
    tree.root.left.right = TreeNode(1)
    tree.root.right.left = TreeNode(12)
    tree.root.left.left = TreeNode(8)
    tree.root.left.left.left = TreeNode(10)
    tree.root.left.left.right = TreeNode(30)
    tree.root.right.left.right = TreeNode(4)
    tree.root.right.left.left = TreeNode(7)
    tree.root.right.right.right = TreeNode(8)
    #  Given Binary Tree
    #  -----------------------
    #          2
    #         / \
    #        /   \ 
    #       /     \
    #      4       10
    #     / \      / \
    #    8   1    12  6
    #   / \      /  \  \
    #  10  30   7    4  8
    #  ----------------------
    #  Even node path from root to every leaf node
    #  2->4->8->10 
    #  2->4->8->30   
    #  2->10->12->4 
    #  2->10->6->8 
    #  -----------
    #  Result : 4 (Total path)
    #  Count resultant node
    counter = tree.countEvenNodePath(tree.root)
    #  Display calculated result
    print(counter)


if __name__=="__main__":
    main()

Output

4

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment