mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0222.完全二叉树的节点个数.md Scala版本
This commit is contained in:
@ -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>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user