Check for continuous binary tree in ruby
Ruby program for Check for continuous binary tree. Here problem description and explanation.
# Ruby program for
# Check if binary tree is continuous tree
# Using recursion
# Binary Tree Node
class TreeNode
# Define the accessor and reader of class TreeNode
attr_reader :data, :left, :right
attr_accessor :data, :left, :right
def initialize(data)
# Set node value
self.data = data
self.left = nil
self.right = nil
end
end
class BinaryTree
# Define the accessor and reader of class BinaryTree
attr_reader :root
attr_accessor :root
def initialize()
self.root = nil
end
def absValue(num)
if (num < 0)
return -num
end
return num
end
# Check tree is continuous or not
def isContinuous(node)
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
end
if (self.isContinuous(node.left) &&
self.isContinuous(node.right))
return true
end
# When node value is not satisfied
# continuous tree properties
return false
end
return true
end
end
def main()
# Create new tree
tree = BinaryTree.new()
# Binary Tree
# ------------
# 5
# / \
# 4 4
# / / \
# 3 5 3
# \
# 2
# Add tree node
tree.root = TreeNode.new(5)
tree.root.left = TreeNode.new(4)
tree.root.right = TreeNode.new(4)
tree.root.left.left = TreeNode.new(3)
tree.root.right.right = TreeNode.new(3)
tree.root.right.left = TreeNode.new(5)
tree.root.left.left.right = TreeNode.new(2)
if (tree.isContinuous(tree.root) == true)
print("Continuous Tree \n")
else
print("Not Continuous Tree \n")
end
# 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 \n")
else
print("Not Continuous Tree \n")
end
end
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