/**
* 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);
}
}