给定 bin 树 defn :
// a binary tree node
case class Node( var data:(Int),
left:Option[Node],
right:Option[Node]
)
我需要得到二叉树的顺序树遍历。例如:
val testtree = Node( (3),
None,
Some(Node( (5),
Some(Node( (1),
None,
None )),
Some(Node( (9),
None,
Some(Node( (15),
None,
None )) )) )) )
为了这棵树 shd 是:3,5,1,9,15
我试过的代码:
def inOrder(t: Node): Unit ={
def print(data:Int,t:Option[Node]):Unit={
if(t!=None)
{
print(data,t.left)
Console.print(data)
print(data,t.right)
}
}
print(t.data,t)
}
但它不工作。有人可以帮我吗。
完整代码:
case class Node( var data:(Int),
left:Option[Node],
right:Option[Node]
)
object Ch15 {
def main( args:Array[String] ) = {
val tree =Node( (3), None,Some(Node( (5), Some(Node( (1), None, None )), Some(Node( (9), None,Some(Node( (15), None, None )) )) )) )
inOrder( tree )
}
def inOrder(t: Node): Unit ={
def print(data:Int,t:Option[Node]):Unit={
if(t!=None)
{
print(data,t.left)
Console.print(data)
print(data,t.right)
}
}
print(t.data,t)
}
}