Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1391 from wzqwtt/tree08
Browse files Browse the repository at this point in the history
添加(0222.完全二叉树的节点个数、0257.二叉树的所有路径)Scala版本
  • Loading branch information
youngyangyang04 authored Jun 23, 2022
2 parents abe1ec3 + 45a3c91 commit a1e9f25
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
63 changes: 63 additions & 0 deletions problems/0222.完全二叉树的节点个数.md
Original file line number Diff line number Diff line change
Expand Up @@ -646,5 +646,68 @@ func countNodes(_ root: TreeNode?) -> Int {
}
```

## Scala

递归:
```scala
object Solution {
def countNodes(root: TreeNode): Int = {
if(root == null) return 0
1 + countNodes(root.left) + countNodes(root.right)
}
}
```

层序遍历:
```scala
object Solution {
import scala.collection.mutable
def countNodes(root: TreeNode): Int = {
if (root == null) return 0
val queue = mutable.Queue[TreeNode]()
var node = 0
queue.enqueue(root)
while (!queue.isEmpty) {
val len = queue.size
for (i <- 0 until len) {
node += 1
val curNode = queue.dequeue()
if (curNode.left != null) queue.enqueue(curNode.left)
if (curNode.right != null) queue.enqueue(curNode.right)
}
}
node
}
}
```

利用完全二叉树性质:
```scala
object Solution {
def countNodes(root: TreeNode): Int = {
if (root == null) return 0
var leftNode = root.left
var rightNode = root.right
// 向左向右往下探
var leftDepth = 0
while (leftNode != null) {
leftDepth += 1
leftNode = leftNode.left
}
var rightDepth = 0
while (rightNode != null) {
rightDepth += 1
rightNode = rightNode.right
}
// 如果相等就是一个满二叉树
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1
}
// 如果不相等就不是一个完全二叉树,继续向下递归
countNodes(root.left) + countNodes(root.right) + 1
}
}
```

-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
30 changes: 30 additions & 0 deletions problems/0257.二叉树的所有路径.md
Original file line number Diff line number Diff line change
Expand Up @@ -702,5 +702,35 @@ func binaryTreePaths(_ root: TreeNode?) -> [String] {
}
```

Scala:

递归:
```scala
object Solution {
import scala.collection.mutable.ListBuffer
def binaryTreePaths(root: TreeNode): List[String] = {
val res = ListBuffer[String]()
def traversal(curNode: TreeNode, path: ListBuffer[Int]): Unit = {
path.append(curNode.value)
if (curNode.left == null && curNode.right == null) {
res.append(path.mkString("->")) // mkString函数: 将数组的所有值按照指定字符串拼接
return // 处理完可以直接return
}

if (curNode.left != null) {
traversal(curNode.left, path)
path.remove(path.size - 1)
}
if (curNode.right != null) {
traversal(curNode.right, path)
path.remove(path.size - 1)
}
}
traversal(root, ListBuffer[Int]())
res.toList
}
}
```

-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 comments on commit a1e9f25

Please sign in to comment.