着实有点抽象
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
class Solution {
//平衡二叉树
func isBalanced(_ root: TreeNode?) -> Bool {
return getHeight(root) >= 0
}
func getHeight(_ node:TreeNode?) -> Int {
guard let nd = node else {
return 0
}
let lh = getHeight(nd.left)
let rh = getHeight(nd.right)
if(lh >= 0 && rh >= 0 && abs(lh - rh) <= 1 ){
return max(lh, rh) + 1
}else{
return -1
}
}
}