/*
* A simple groovy implementation to create a Binary Tree
* and to perform inorder traversal
*/
class Node{
Node left, right
int data
Node(data){
this.data = data
left = null
right = null
}
}
class BTree{
static def insert(Node node, val){
if(val < node.data){
if(node.left == null){
node.left = new Node(val)
println "inserting $val to the left of $node.data"
}
else insert(node.left, val)
}
else if(val > node.data){
if(node.right == null){
node.right = new Node(val)
println "inserting $val to the right of $node.data"
}
else insert(node.right, val)
}
}
//left, root, right
static def printInOrder(Node node){
if(node == null) return
else{
printInOrder(node.left)
println node.data
printInOrder(node.right)
}
}
}
//Shift to main if you aren't running this as a groovy script
def root = new Node(25)
BTree.insert(root, 10)
BTree.insert(root, 30)
BTree.insert(root, 24)
BTree.insert(root, 299)
BTree.insert(root, 266)
BTree.insert(root, 121)
BTree.insert(root, 920)
//Inorder traversal of the entered elements
BTree.printInOrder(root)
0 comments:
Post a Comment