Skip to content

Commit f93d313

Browse files
committed
Add cache code
1 parent dfa47a0 commit f93d313

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

110/step4.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// 繰り返し呼ばれるheightについて、キャッシュで高速化を試みたがむしろ低速化した
2+
class Solution {
3+
public:
4+
bool isBalanced(TreeNode* root) {
5+
if (!root) {
6+
return true;
7+
}
8+
9+
int left_height = height(root->left);
10+
int right_height = height(root->right);
11+
12+
return abs(right_height - left_height) <= 1 && isBalanced(root->left) && isBalanced(root->right);
13+
}
14+
15+
map<TreeNode*, int> height_cache;
16+
int height(TreeNode* root, int base_height = 0) {
17+
if (height_cache.count(root)) {
18+
return height_cache[root];
19+
}
20+
if (!root) {
21+
return base_height;
22+
}
23+
24+
int left_height = height(root->left);
25+
int right_height = height(root->right);
26+
27+
height_cache[root] = max(left_height, right_height)+1;
28+
return height_cache[root];
29+
}
30+
};

0 commit comments

Comments
 (0)