Posted on by Kalkicode
Code Binary Tree

Count complete even nodes path of binary tree in c#

All even nodes path from root to leaf in binary tree

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

// Include namespace system
using System;
/* 
  Csharp program for
  Count even node paths in Binary Tree
*/
// Binary Tree node
public class TreeNode
{
	public int data;
	public TreeNode left;
	public TreeNode right;
	public TreeNode(int data)
	{
		// Set node value
		this.data = data;
		this.left = null;
		this.right = null;
	}
}
public class BinaryTree
{
	public TreeNode root;
	public BinaryTree()
	{
		// Set initial tree root
		this.root = null;
	}
	// Count all paths from root to leaf
	// which containing all Even nodes
	public int countEvenNodePath(TreeNode node)
	{
		if (node == null || node.data % 2 != 0)
		{
			// When tree node is null or
			// its contain Odd value.
			return 0;
		}
		else
		{
			if (node.left == null && 
                node.right == null)
			{
				// When get leaf node
				return 1;
			}
			return this.countEvenNodePath(node.left) +
              this.countEvenNodePath(node.right);
		}
	}
	public static void Main(String[] args)
	{
		// New binary tree
		var tree = new BinaryTree();
		/*
		  Construct Binary Tree
		  -----------------------
		          2
		         / \
		        /   \ 
		       /     \
		      4       10
		     / \      / \
		    8   1    12  6
		   / \      /  \  \
		  10  30   7    4  8
		*/
		// Add tree node
		tree.root = new TreeNode(2);
		tree.root.left = new TreeNode(4);
		tree.root.right = new TreeNode(10);
		tree.root.right.right = new TreeNode(6);
		tree.root.left.right = new TreeNode(1);
		tree.root.right.left = new TreeNode(12);
		tree.root.left.left = new TreeNode(8);
		tree.root.left.left.left = new TreeNode(10);
		tree.root.left.left.right = new TreeNode(30);
		tree.root.right.left.right = new TreeNode(4);
		tree.root.right.left.left = new TreeNode(7);
		tree.root.right.right.right = new 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
		var counter = tree.countEvenNodePath(tree.root);
		// Display calculated result
		Console.Write(counter);
	}
}

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