Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 13615d1

Browse files
committed
Add solution 110.
1 parent 3d645ea commit 13615d1

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* public $val = null;
5+
* public $left = null;
6+
* public $right = null;
7+
* function __construct($value) { $this->val = $value; }
8+
* }
9+
*/
10+
class Solution {
11+
12+
/**
13+
* @param TreeNode $root
14+
* @return Boolean
15+
*/
16+
function isBalanced($root) {
17+
return $root == null || self::checkDepth($root) != -1;
18+
}
19+
20+
function checkDepth($root) {
21+
$lh = $root->left == null ? 0 : self::checkDepth($root->left);
22+
$rh = $root->right == null ? 0 : self::checkDepth($root->right);
23+
// Left subtree or right subtree is unbalanced
24+
if ($lh == -1 || $rh == -1) return -1;
25+
// This tree is unbalanced
26+
if ($lh - $rh > 1 || $lh - $rh < -1) return -1;
27+
// Return depth of this tree
28+
return max($lh, $rh) + 1;
29+
}
30+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /