Skip to content

Commit 84e046e

Browse files
committed
222
1 parent 897aa85 commit 84e046e

File tree

1 file changed

+21
-1
lines changed
  • leetcode/222. Count Complete Tree Nodes

1 file changed

+21
-1
lines changed

leetcode/222. Count Complete Tree Nodes/README.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public:
6060
6161
## Solution 2.
6262
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.
6464
6565
```cpp
6666
// OJ: https://leetcode.com/problems/count-complete-tree-nodes/
@@ -90,4 +90,24 @@ public:
9090
return count(root);
9191
}
9292
};
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+
};
93113
```

0 commit comments

Comments
 (0)