Leetcode 222. Count Complete Tree Nodes
Given the root of a complete binary tree, return the number of the nodes in the tree.
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1
and 2^h
nodes inclusive at the last level h
.
int countNodes(TreeNode* root)
?/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) return 0;
int left_depth = getDepth(root->left);
int right_depth = getDepth(root->right);
if (left_depth == right_depth) {
return (1 << left_depth) + countNodes(root->right);
} else {
return (1 << right_depth) + countNodes(root->left);
}
}
private:
int getDepth(TreeNode* node) {
int depth = 0;
while (node) {
depth++;
node = node->left;
}
return depth;
}
};
d
is 2^d - 1
.1 << depth
.O(log n)
where n
is the number of nodes.O(log^2 n)
because at each level of recursion, depth calculation is O(log n)
and there are O(log n)
levels due to the halving nature of each step.This approach leverages the properties of complete binary trees to achieve an efficient counting method.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?