LEETCODE - 0100 - 平衡二叉树

365 阅读1分钟

原文链接

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

  3
 / \
9  20
  /  \
 15   7

返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

      1
     / \
    2   2
   / \
  3   3
 / \
4   4

返回 false 。

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/ba… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

使用递归求解,递归过程中每一步求解方案如下

  1. 判断树是否为空,为空返回true,因为空树肯定是平衡的。
  2. 判断树的左、右子节点是否平衡。
    • 左节点平衡
    • 右节点平衡
    • 左右深度差不超过1
  3. 如果满足2步骤的条件,返回真,深度为左、右子树的深度+1

完整代码

Golang

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
}

Common Lisp

(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)))))