Count complete odd nodes path of binary tree in swift

Swift program for Count complete odd nodes path of binary tree. Here mentioned other language solution.
import Foundation
/*
Swift 4 program for
Count odd paths in Binary Tree
*/
// Binary Tree node
class TreeNode
{
var data: Int;
var left: TreeNode? ;
var right: TreeNode? ;
init(_ data: Int)
{
// Set node value
self.data = data;
self.left = nil;
self.right = nil;
}
}
class BinaryTree
{
var root: TreeNode? ;
init()
{
self.root = nil;
}
// Count all paths from root to leaf
// which containing all Odd nodes
func countOddNodePath(_ node: TreeNode? ) -> Int
{
if (node == nil || node!.data % 2 == 0)
{
// When tree node is null or
// its contain even value
return 0;
}
else
{
if (node!.left == nil && node!.right == nil)
{
// When get leaf node And
// path contain all Odd nodes
return 1;
}
return self.countOddNodePath(node!.left) +
self.countOddNodePath(node!.right);
}
}
static func main()
{
// New of binary tree
let tree: BinaryTree = BinaryTree();
/*
Construct Binary Tree
-----------------------
5
/ \
/ \
3 9
/ \ / \
7 6 1 3
/ \ / \
10 3 7 4
*/
// Add tree node
tree.root = TreeNode(5);
tree.root!.left = TreeNode(3);
tree.root!.right = TreeNode(9);
tree.root!.right!.right = TreeNode(3);
tree.root!.left!.right = TreeNode(6);
tree.root!.right!.left = TreeNode(1);
tree.root!.left!.left = TreeNode(7);
tree.root!.left!.left!.left = TreeNode(10);
tree.root!.left!.left!.right = TreeNode(3);
tree.root!.right!.left!.right = TreeNode(4);
tree.root!.right!.left!.left = 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.
print(tree.countOddNodePath(tree.root));
}
}
BinaryTree.main();
Output
3
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