mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
添加 110.平衡二叉树 Swift版本
This commit is contained in:
@ -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>
|
||||
|
Reference in New Issue
Block a user