Check if all leaf nodes are at same level in ruby

Ruby program for Check if all leaf nodes are at same level. Here problem description and other solutions.

``````#  Ruby program for
#  Check if all leaves are at same level

#  Binary Tree Node
class TreeNode
# Define the accessor and reader of class TreeNode
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_accessor :root, :depth
def initialize()
self.root = nil
self.depth = -1
end

def checkLeafHeight(node, level)
if (node != nil)
#  Test node is leaf or not
if (node.left == nil && node.right == nil)
if (self.depth == -1)
#  This is first leaf node
#  Get node level
self.depth = level
elsif(self.depth != level)
#  When two leaf nodes is different level
self.depth = -2
return
end

end

if (self.depth != -2)
#  Recursively visit left and right subtree
self.checkLeafHeight(node.left, level + 1)
self.checkLeafHeight(node.right, level + 1)
end

end

end

def isSameLevelLeaf()
self.depth = -1
#  Test
self.checkLeafHeight(self.root, 1)
#  Display result
if (self.depth < 0)
#  Two possible case
#  1) When tree empty
#  2) When leaf node are not same level
print("No\n")
else

#  When leaf node is same level
print("Yes\n")
end

end

end

def main()
#  Create new tree
tree = BinaryTree.new()
#    Make A Binary Tree
#    --------------------
#      1
#     /  \
#    2    3
#   /    /  \
#  4    5    6
# insertion of binary Tree nodes
tree.root = TreeNode.new(1)
tree.root.left = TreeNode.new(2)
tree.root.right = TreeNode.new(3)
tree.root.right.right = TreeNode.new(6)
tree.root.right.left = TreeNode.new(5)
tree.root.left.left = TreeNode.new(4)
tree.isSameLevelLeaf()
tree.root.left.left.left = TreeNode.new(7)
#    -----------------------
#          1
#         /  \
#        2    3
#       /    /  \
#      4    5    6
#     /
#    7
tree.isSameLevelLeaf()
end

main()``````

Output

``````Yes
No
``````

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.