LEETCODE - 0100 - 平衡二叉树

原文连接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… 著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。

解题思路

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

  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)))))
复制代码
相关文章
相关标签/搜索