添加 110.平衡二叉树 Swift版本

This commit is contained in:
极客学伟
2022-01-18 13:18:36 +08:00
parent 6ea6956cd5
commit 3d0ce431d8

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>