gpt4 book ai didi

scala - scala中的二叉树遍历

转载 作者:行者123 更新时间:2023-12-02 17:47:36 25 4
gpt4 key购买 nike

给定 bin 树定义:

// 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 )) )) )) )

这棵树的顺序应该是: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)
}

}

最佳答案

case class Branch(node: Int, left: Option[Branch] = None, right: Option[Branch] = None)

object TreeTraverse extends App {
val branch = Branch(1, Some(Branch(2, Some(Branch(4)), Some(Branch(5)))), Some(Branch(3, Some(Branch(6)), Some(Branch(7)))))

def preOrder(branch: Branch): Unit = {
print(branch.node)
if (branch.left.isDefined) preOrder(branch.left.get)
if (branch.right.isDefined) preOrder(branch.right.get)
}

def inOrder(branch: Branch): Unit = {
if (branch.left.isDefined) inOrder(branch.left.get)
print(branch.node)
if (branch.right.isDefined) inOrder(branch.right.get)
}

def postOrder(branch: Branch): Unit = {
if (branch.left.isDefined) postOrder(branch.left.get)
if (branch.right.isDefined) postOrder(branch.right.get)
print(branch.node)
}

println(" -> PreOrder" + preOrder(branch))
println(" -> InOrder " + inOrder(branch))
println(" -> PostOrder " + postOrder(branch))
}

关于scala - scala中的二叉树遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12772964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com