原文连接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))))) 复制代码