Scala LeetCode 965. 单值二叉树

https://leetcode-cn.com/problems/univalued-binary-tree/

class TreeNode(var _value: Int) {
  var value: Int = _value
  var left: TreeNode = _
  var right: TreeNode = _
}
object Main {
  def isUnivalTree(root: TreeNode): Boolean = {
    var b = List[TreeNode]()
    val x = root._value
    b = root :: b
    while (b.nonEmpty) {
      val t = b.head
      b = b.tail
      if (t.left != null) {
        if (t.left._value != x) {
          return false
        }
        b = t.left :: b
      }
      if (t.right != null) {
        if (t.right._value != x) {
          return false
        }
        b = t.right :: b
      }
    }
    true
  }
  def main(args: Array[String]): Unit = {
    val root = new TreeNode(0)
    root.right = new TreeNode(0)
    assert(isUnivalTree(root), true)
  }
}

继续总结

  1. 似乎是如果没有写 apply的类,需要用到new
  2. stack 已经被scala抛弃了,用var List(这个单开一篇文章讲)
  3. 大部分集合类都有 nonEmpty方法,真的是函数多
  4. 在定义类成员变量初始值时可以用 _ 代替 null

猜你喜欢

转载自blog.csdn.net/YYecust/article/details/85596813