Check for continuous binary tree in swift
Swift program for Check for continuous binary tree. Here problem description and other solutions.
import Foundation
/*
Swift 4 program for
Check if binary tree is continuous tree
Using recursion
*/
// 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;
}
func absValue(_ num: Int) -> Int
{
if (num < 0)
{
return -num;
}
return num;
}
// Check tree is continuous or not
func isContinuous(_ node: TreeNode? ) -> Bool
{
if (node != nil)
{
if ((node!.left != nil &&
self.absValue(node!.data - node!.left!.data) != 1) ||
(node!.right != nil &&
self.absValue(node!.data - node!.right!.data) != 1))
{
// Case
// When fail continuous tree rule
return false;
}
if (self.isContinuous(node!.left) &&
self.isContinuous(node!.right))
{
return true;
}
// When node value is not satisfied
// continuous tree properties
return false;
}
return true;
}
static func main()
{
// Create new tree
let tree: BinaryTree = BinaryTree();
/*
Binary Tree
------------
5
/ \
4 4
/ / \
3 5 3
\
2
*/
// Add tree node
tree.root = TreeNode(5);
tree.root!.left = TreeNode(4);
tree.root!.right = TreeNode(4);
tree.root!.left!.left = TreeNode(3);
tree.root!.right!.right = TreeNode(3);
tree.root!.right!.left = TreeNode(5);
tree.root!.left!.left!.right = TreeNode(2);
if (tree.isContinuous(tree.root) == true)
{
print("Continuous Tree ");
}
else
{
print("Not Continuous Tree ");
}
// Case 2
/*
5
/ \
4 4
/ / \
3 5 3
\
1 <--- change value
*/
tree.root!.left!.left!.right!.data = 1;
if (tree.isContinuous(tree.root) == true)
{
print("Continuous Tree ");
}
else
{
print("Not Continuous Tree ");
}
}
}
BinaryTree.main();
Output
Continuous Tree
Not Continuous Tree
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