File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments