diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index ba7acc5a..746d45cc 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -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 + } +} +``` + -----------------------