添加 222.完全二叉树的节点个数 Swift版本

This commit is contained in:
极客学伟
2022-01-13 14:08:26 +08:00
parent f292f580c3
commit c6c3972408

View File

@ -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
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>