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)))))
複製代碼
相關文章
相關標籤/搜索