原文連接markdown
給定一個二叉樹,判斷它是不是高度平衡的二叉樹。網絡
本題中,一棵高度平衡二叉樹定義爲:oop
一個二叉樹每一個節點的左右兩個子樹的高度差的絕對值不超過1。post
示例 1:spa
給定二叉樹 [3,9,20,null,null,15,7]code
3
/ \
9 20
/ \
15 7
複製代碼
返回 true 。orm
示例 2:遞歸
給定二叉樹 [1,2,2,3,3,null,null,4,4]ci
1
/ \
2 2
/ \
3 3
/ \
4 4
複製代碼
返回 false 。leetcode
來源:力扣(LeetCode) 連接:leetcode-cn.com/problems/ba… 著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。
使用遞歸求解,遞歸過程當中每一步求解方案以下
func IsBalanced(root *leetcode.TreeNode) bool { ok, _ := bst(root) return ok } func bst(root *leetcode.TreeNode) (bool, float64) { if root == nil { return true, 0 } leftBalanced, leftDepth := bst(root.Left) rightBalanced, rightDepth := bst(root.Right) if !leftBalanced || !rightBalanced || math.Abs(leftDepth-rightDepth) > 1 { return false, 0 } return true, math.Max(leftDepth, rightDepth) + 1 } 複製代碼
(defun is-balanced (root) (if (null root) (list t 0) (let ((l (is-balanced (nth 0 root))) (r (is-balanced (nth 1 root)))) (if (and (nth 0 l) (nth 0 r) (<= (abs (- (nth 1 l) (nth 1 r))) 1)) (list t (+ (max (nth 1 l) (nth 1 r)) 1)) (list nil 0))))) 複製代碼