File tree Expand file tree Collapse file tree 1 file changed +21
-1
lines changed
leetcode/222. Count Complete Tree Nodes Expand file tree Collapse file tree 1 file changed +21
-1
lines changed Original file line number Diff line number Diff line change @@ -60,7 +60,7 @@ public:
60
60
61
61
## Solution 2.
62
62
63
- Minor optimization which prevents us from recomputing the lengths that we've already know .
63
+ Minor optimization which prevents us from recomputing the lengths that we've already known .
64
64
65
65
```cpp
66
66
// OJ: https://leetcode.com/problems/count-complete-tree-nodes/
@@ -90,4 +90,24 @@ public:
90
90
return count(root);
91
91
}
92
92
};
93
+ ```
94
+
95
+ ## Solution 3.
96
+
97
+ ``` cpp
98
+ // OJ: https://leetcode.com/problems/count-complete-tree-nodes/
99
+ // Author: github.com/lzl124631x
100
+ // Time: O(H^2)
101
+ // Space: O(H)
102
+ // Ref: https://leetcode.com/problems/count-complete-tree-nodes/discuss/61958/Concise-Java-solutions-O(log(n)2)
103
+ class Solution {
104
+ int height(TreeNode * root) {
105
+ return root ? 1 + height(root->left) : -1;
106
+ }
107
+ public:
108
+ int countNodes(TreeNode* root) {
109
+ int h = height(root);
110
+ return h < 0 ? 0 : (height(root->right) + 1 == h ? (1 << h) + countNodes(root->right) : (1 << (h - 1)) + countNodes(root->left));
111
+ }
112
+ };
93
113
```
You can’t perform that action at this time.
0 commit comments