# Detect next node at same level of a key in binary tree in ruby

Ruby program for Detect next node at same level of a key in binary tree. Here more solutions.

``````#  Ruby program for
#  Find the next node of the key at the same
#  level in the binary tree

#  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, :status, :result
def initialize()
self.root = nil
self.status = -1
self.result = nil
end

#  Method which are find next node of same level
def findNextNode(temp, level, node)
if (temp != nil)
if (self.status == -1 && temp.data == node)
#  When found node value
self.status = level
elsif(self.status == level && self.result == nil)
#  Next node of same level
self.result = temp
end

#  Visit to left subtree
self.findNextNode(temp.left, level + 1, node)
#  Visit to right subtree
self.findNextNode(temp.right, level + 1, node)
end
end

#  This are handling the request of to finding next
#  node in same level by given node
def nextNode(node)
#  Reset the result indicator
self.status = -1
self.result = nil
#  Find next node
self.findNextNode(self.root, 0, node)
print("\n Node : ", node, "\n")
print(" Result : ")
#  Test Case
if (self.status == -1)
#  Case A
#  When node values are not exist
elsif(self.result == nil)
#  Case B
print("None\n")
else
#  Case C
#  When next node are exist
print(self.result.data, "\n")
end
end
end

def main()
#  Create new tree
tree = BinaryTree.new()
#   Make A Binary Tree
#  ---------------------
#        1
#       / \
#      /   \
#     /     \
#    2       4
#   /       / \
#  /       /   \
#  3      6     5
#   \      \   /
#    7      8 11
#  Add node in Binary Tree
tree.root = TreeNode.new(1)
tree.root.left = TreeNode.new(2)
tree.root.left.left = TreeNode.new(3)
tree.root.left.left.right = TreeNode.new(7)
tree.root.right = TreeNode.new(4)
tree.root.right.right = TreeNode.new(5)
tree.root.right.right.left = TreeNode.new(11)
tree.root.right.left = TreeNode.new(6)
tree.root.right.left.right = TreeNode.new(8)
#  Testing
tree.nextNode(3)
tree.nextNode(7)
tree.nextNode(6)
tree.nextNode(5)
tree.nextNode(8)
tree.nextNode(1)
end

main()``````

Output

`````` Node : 3
Result : 6

Node : 7
Result : 8

Node : 6
Result : 5

Node : 5
Result : None

Node : 8
Result : 11

Node : 1
Result : None
``````

## 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.