Merge pull request #1036 from qxuewei/master

添加 110.平衡二叉树 Swift版本
This commit is contained in:
程序员Carl
2022-01-26 14:19:06 +08:00
committed by GitHub
2 changed files with 93 additions and 0 deletions

View File

@ -730,5 +730,33 @@ bool isBalanced(struct TreeNode* root){
} }
``` ```
## Swift:
>递归
```swift
func isBalanced(_ root: TreeNode?) -> Bool {
// -1 已经不是平衡二叉树
return getHeight(root) == -1 ? false : true
}
func getHeight(_ root: TreeNode?) -> Int {
guard let root = root else {
return 0
}
let leftHeight = getHeight(root.left)
if leftHeight == -1 {
return -1
}
let rightHeight = getHeight(root.right)
if rightHeight == -1 {
return -1
}
if abs(leftHeight - rightHeight) > 1 {
return -1
} else {
return 1 + max(leftHeight, rightHeight)
}
}
```
----------------------- -----------------------
<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>

View File

@ -581,7 +581,72 @@ var binaryTreePaths = function(root) {
}; };
``` ```
Swift:
> 递归/回溯
```swift
func binaryTreePaths(_ root: TreeNode?) -> [String] {
var res = [String]()
guard let root = root else {
return res
}
var path = [Int]()
_binaryTreePaths(root, path: &path, res: &res)
return res
}
func _binaryTreePaths(_ root: TreeNode, path: inout [Int], res: inout [String]) {
path.append(root.val)
if root.left == nil && root.right == nil {
var str = ""
for i in 0 ..< path.count - 1 {
str.append("\(path[i])->")
}
str.append("\(path.last!)")
res.append(str)
return
}
if let left = root.left {
_binaryTreePaths(left, path: &path, res: &res)
path.removeLast()
}
if let right = root.right {
_binaryTreePaths(right, path: &path, res: &res)
path.removeLast()
}
}
```
> 迭代
```swift
func binaryTreePaths(_ root: TreeNode?) -> [String] {
var res = [String]()
guard let root = root else {
return res
}
var stackNode = [TreeNode]()
stackNode.append(root)
var stackStr = [String]()
stackStr.append("\(root.val)")
while !stackNode.isEmpty {
let node = stackNode.popLast()!
let str = stackStr.popLast()!
if node.left == nil && node.right == nil {
res.append(str)
}
if let left = node.left {
stackNode.append(left)
stackStr.append("\(str)->\(left.val)")
}
if let right = node.right {
stackNode.append(right)
stackStr.append("\(str)->\(right.val)")
}
}
return res
}
```
----------------------- -----------------------
<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>