Skip to main content

Count complete odd nodes path of binary tree in c#

All odd nodes path from root to leaf in binary tree

Csharp program for Count complete odd nodes path of binary tree. Here more solutions.

// Include namespace system
using System;
/* 
  Csharp program for
  Count odd 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 Odd nodes
	public int countOddNodePath(TreeNode node)
	{
		if (node == null || node.data % 2 == 0)
		{
			// When tree node is null or
			// its contain even value
			return 0;
		}
		else
		{
			if (node.left == null && node.right == null)
			{
				// When get leaf node And
				// path contain all Odd nodes
				return 1;
			}
			return this.countOddNodePath(node.left) +
              this.countOddNodePath(node.right);
		}
	}
	public static void Main(String[] args)
	{
		// New of binary tree
		var tree = new BinaryTree();
		/*
		  Construct Binary Tree
		  -----------------------
		         5
		        /  \ 
		       /    \
		      3      9
		     / \    / \
		    7   6  1   3
		   / \    / \   
		  10  3  7   4
		*/
		// Add tree node
		tree.root = new TreeNode(5);
		tree.root.left = new TreeNode(3);
		tree.root.right = new TreeNode(9);
		tree.root.right.right = new TreeNode(3);
		tree.root.left.right = new TreeNode(6);
		tree.root.right.left = new TreeNode(1);
		tree.root.left.left = new TreeNode(7);
		tree.root.left.left.left = new TreeNode(10);
		tree.root.left.left.right = new TreeNode(3);
		tree.root.right.left.right = new TreeNode(4);
		tree.root.right.left.left = new TreeNode(7);
		/*
		  Given Binary Tree
		  -----------------------
		         5
		        /  \ 
		       /    \
		      3      9
		     / \    / \
		    7   6  1   3
		   / \    / \   
		  10  3  7   4
		  Here
		  Odd path from root to leaf
		  -----------------------
		         5
		        /  \ 
		       /    \
		      3      9
		     /      / \
		    7      1   3
		     \    /     
		      3  7    
		  ---------------------
			5->3->7->3    
			5->9->1->7  
		    5->9->3  
		  ----------------------
		  Result : 3 [number of path]
		*/
		// Count odd nodes paths from root
		// to leaf in a binary tree.
		Console.WriteLine(tree.countOddNodePath(tree.root));
	}
}

Output

3




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