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

Go program for Detect next node at same level of a key in binary tree. Here mentioned other language solution.

``````package main
import "fmt"
/*
Go program for
Find the next node of the key at the same
level in the binary tree
*/
// Binary Tree node
type TreeNode struct {
data int
left * TreeNode
right * TreeNode
}
func getTreeNode(data int) * TreeNode {
// return new TreeNode
return &TreeNode {
data,
nil,
nil,
}
}
type BinaryTree struct {
root * TreeNode
status int
result * TreeNode
}
func getBinaryTree() * BinaryTree {
// return new BinaryTree
return &BinaryTree {
nil,
-1,
nil,
}
}
// Method which are find next node of same level
func(this *BinaryTree) findNextNode(temp * TreeNode,
level int, node int) {
if temp != nil {
if this.status == -1 && temp.data == node {
// When found node value
this.status = level
} else if this.status == level && this.result == nil {
// Next node of same level
this.result = temp
}
// Visit to left subtree
this.findNextNode(temp.left, level + 1, node)
// Visit to right subtree
this.findNextNode(temp.right, level + 1, node)
}
}
// This are handling the request of to finding next
// node in same level by given node
func(this BinaryTree) nextNode(node int) {
// Reset the result indicator
this.status = -1
this.result = nil
// Find next node
this.findNextNode(this.root, 0, node)
fmt.Println("\n Node : ", node)
fmt.Print(" Result : ")
// Test Case
if this.status == -1 {
// Case A
// When node values are not exist
} else if this.result == nil {
// Case B
fmt.Println("None")
} else {
// Case C
// When next node are exist
fmt.Println(this.result.data)
}
}
func main() {
// Create new tree
var tree * BinaryTree = getBinaryTree()
/*
Make A Binary Tree
---------------------
1
/ \
/   \
/     \
2       4
/       / \
/       /   \
3      6     5
\      \   /
7      8 11

*/
// Add node in Binary Tree
tree.root = getTreeNode(1)
tree.root.left = getTreeNode(2)
tree.root.left.left = getTreeNode(3)
tree.root.left.left.right = getTreeNode(7)
tree.root.right = getTreeNode(4)
tree.root.right.right = getTreeNode(5)
tree.root.right.right.left = getTreeNode(11)
tree.root.right.left = getTreeNode(6)
tree.root.right.left.right = getTreeNode(8)
// Testing
tree.nextNode(3)
tree.nextNode(7)
tree.nextNode(6)
tree.nextNode(5)
tree.nextNode(8)
tree.nextNode(1)
}``````

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.