110. Balanced Binary Tree

檢查二元樹是否平衡,計算最左與罪右節點最大深度相差是否大於 1,再向中間計算左右節點深度相差是否大於 1

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root
     * @return Boolean
     */
    function isBalanced($root) {
        if ($root === null) {
            return true;
        }

        $left = $this->getMaxDepth($root->left);
        $right = $this->getMaxDepth($root->right);

        return abs($left - $right) <= 1 && $this->isBalanced($root->left) && $this->isBalanced($root->right);
    }

    function getMaxDepth($node): int {
        if ($node === null) {
            return 0;
        }

        $left = 1 + $this->getMaxDepth($node->left);
        $right = 1 + $this->getMaxDepth($node->right);

        return max($left, $right);
    }
}

Last updated