From c6c39724089a07c5cdd809cca27dd46047fc998f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Thu, 13 Jan 2022 14:08:26 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20222.=E5=AE=8C=E5=85=A8?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E8=8A=82=E7=82=B9=E4=B8=AA?= =?UTF-8?q?=E6=95=B0=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0222.完全二叉树的节点个数.md | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 754a6094..8d38bace 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -522,5 +522,73 @@ int countNodes(struct TreeNode* root){ } ``` +## Swift: + +> 递归 +```swift +func countNodes(_ root: TreeNode?) -> Int { + return _countNodes(root) +} +func _countNodes(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + let leftCount = _countNodes(root.left) + let rightCount = _countNodes(root.right) + return 1 + leftCount + rightCount +} +``` + +> 层序遍历 +```Swift +func countNodes(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + var res = 0 + var queue = [TreeNode]() + queue.append(root) + while !queue.isEmpty { + let size = queue.count + for _ in 0 ..< size { + let node = queue.removeFirst() + res += 1 + if let left = node.left { + queue.append(left) + } + if let right = node.right { + queue.append(right) + } + } + } + return res +} +``` + +> 利用完全二叉树性质 +```Swift +func countNodes(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + var leftNode = root.left + var rightNode = root.right + var leftDepth = 0 + var rightDepth = 0 + while leftNode != nil { + leftNode = leftNode!.left + leftDepth += 1 + } + while rightNode != nil { + rightNode = rightNode!.right + rightDepth += 1 + } + if leftDepth == rightDepth { + return (2 << leftDepth) - 1 + } + return countNodes(root.left) + countNodes(root.right) + 1 +} +``` + -----------------------