Skip to content

Instantly share code, notes, and snippets.

@hpcx82
Created June 4, 2012 15:19
Show Gist options
  • Select an option

  • Save hpcx82/2869012 to your computer and use it in GitHub Desktop.

Select an option

Save hpcx82/2869012 to your computer and use it in GitHub Desktop.
Use scala to exchange left/right children of a binary tree
package handson
class Node(l: Node, r: Node, n: String)
{
var left = l
var right = r
var name = n
}
package handson
object Program
{
def printTree(root: Node)
{
print(root.name)
print(" ")
if(root.left != null) printTree(root.left)
if(root.right != null) printTree(root.right)
}
def dotTree(root: Node)
{
println("digraph tree {")
dotTreeRecur(root)
println("}")
}
def dotTreeRecur(root: Node)
{
if(root.left != null)
{
println("\t" + root.name + " -> " + root.left.name)
dotTreeRecur(root.left)
}
if(root.right != null)
{
println("\t" + root.name + " -> " + root.right.name)
dotTreeRecur(root.right)
}
}
def exchange(root: Node)
{
val tmp = root.left
root.left = root.right
root.right = tmp
if(root.left != null) exchange(root.left)
if(root.right != null) exchange(root.right)
}
def main(args: Array[String]): Unit =
{
// construct the tree
val nd = new Node(null, null, "D")
val ne = new Node(null, null, "E")
val nf = new Node(null, null, "F")
val ng = new Node(null, null, "G")
val nb = new Node(nd, ne, "B")
val nc = new Node(nf, ng, "C")
val na = new Node(nb, nc, "A")
// print - exchange - print
printTree(na)
println()
dotTree(na);
println()
exchange(na)
printTree(na)
println()
dotTree(na);
println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment