简体   繁体   English

Inorder Traversal具有返回值

[英]Inorder Traversal with return value

So I'm doing inorder traversal for a tree, for which the code goes something like this 所以我正在为一棵树进行顺序遍历,代码就是这样的

var traversal:String = ""
def inorder(node: Node): String = {

if (node == null)
  return traversal
inorder(node.leftChild)
traversal += node.label
inorder(node.rightChild)
return traversal
}

I'm facing an issue though (a really stupid one) that when I run it for two nodes (say A and B), the value of traversal obtained while running for A is also included while getting traversal for B. Since it is a recursive function, I cannot define traversal inside the function either. 我现在面临的一个问题,但(一个非常愚蠢的一个),当我运行了两个节点(比如A和B),还包括而对于运行中获得的遍历的价值,同时获得遍历 B.既然是递归函数,我也无法在函数内部定义遍历 Please tell how to do it. 请告诉我们该怎么做。

Your code doesn't compile, because you are trying to re-assign a val . 您的代码无法编译,因为您正在尝试重新分配val A val can only be initialized once and cannot be re-assigned. val只能初始化一次,不能重新分配。 Also, your code is not very Scala-like, because you are using null and return . 此外,您的代码不是很像Scala,因为您使用nullreturn

You should use Option instead of null for values that can potentially be empty. 对于可能为空的值,您应该使用Option而不是null null really only exists for interoperability with Java and should be avoided in pure Scala code. null实际上只存在与Java的互操作性,应该在纯Scala代码中避免使用。

You do not need to use the return keyword; 您不需要使用return关键字; the last expression that's executed in a method is automatically the method's return value. 在方法中执行的最后一个表达式自动是方法的返回值。

This would be a better implementation (still using null - you'll need to modify your Node class to get rid of that): 这将是一个更好的实现(仍然使用null - 您需要修改您的Node类以摆脱它):

def inorder(node: Node): String =
  if (node == null) ""
  else inorder(node.leftChild) + node.label + inorder(node.rightChild)

When using Option : 使用Option

case class Node(leftChild: Option[Node], label: String, rightChild: Option[Node])

def inorder(node: Option[Node]): String =
  node map { n => inorder(n.leftChild) + n.label + inorder(n.rightChild) } getOrElse ""

Example use: 使用示例:

scala> val tree = Node(Some(Node(None, "left", None)), "root", Some(Node(None, "right", None)))
tree: Node = Node(Some(Node(None,left,None)),root,Some(Node(None,right,None)))

scala> inorder(Some(tree))
res2: String = leftrootright

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM