上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
}
};
php 解法, 执行用时: 20 ms, 内存消耗: 17.6 MB, 提交时间: 2021-05-10 16:42:58
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($value) { $this->val = $value; }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @return Boolean
*/
function isBalanced($root) {
return $this->recur($root) != -1;
}
function recur($root) {
if ( $root == null ) return 0;
$left = $this->recur($root->left);
if ( $left == -1 ) return -1;
$right = $this->recur($root->right);
if ( $right == -1 ) return -1;
return abs($left - $right) <= 1 ? max($left, $right) + 1 : -1;
}
}