Skip to content

Commit 4fd15c6

Browse files
committed
Add O(N) code without cache
1 parent 91c1a93 commit 4fd15c6

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

110/step5.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// キャッシュを使わずにO(N)となるコード
2+
class Solution {
3+
public:
4+
bool isBalanced(TreeNode* root) {
5+
return getHeight(root) != -1;
6+
}
7+
8+
int getHeight(TreeNode* root) {
9+
if (!root) {
10+
return 0;
11+
}
12+
13+
int left_height = getHeight(root->left);
14+
if (left_height == -1) {
15+
return -1;
16+
}
17+
18+
int right_height = getHeight(root->right);
19+
if (right_height == -1) {
20+
return -1;
21+
}
22+
23+
if (abs(left_height - right_height) > 1) {
24+
return -1;
25+
}
26+
27+
return max(left_height, right_height) + 1;
28+
}
29+
30+
};

0 commit comments

Comments
 (0)