Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree 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 2h nodes inclusive at the last level h.
基本思路:折半
判断当前子树是否为满二叉树,如果是,则应用公式,根据高度求结点。2 ^ (h+1) - 1, h 从0 开始,即根为0层
如果不是满二叉树,则递归求出左子树和右子树的结点树。
判断是否为满二叉树,是通过从左子树往下遍历求高度,和通过右子树往下求高度,最后作比较完成的。
每次折半时,左子树和右子树中,必有一个是满二叉树。故可每次完成一半结点的统计。
时间复杂度为O(log(n)^2)
在leetcode上实际执行时间为128ms。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) return 0;
int level = -1;
TreeNode *left = root;
TreeNode *right = root;
while (right) {
++level;
left = left->left;
right = right->right;
}
if (!left)
return (1 << level+1) - 1;
else
return 1 + countNodes(root->left) + countNodes(root->right);
}
};
算法二,折半
算法一中,每次递归时,都会进行两次求高度运算。
此算法将省去一次高度运算。在进行子树细分时,高度是逐渐递减的,因此左边子树的高度无须每次进行运算。
但是思路与算法一略有差别。
1. 求出右子树的高度。
2. 如果此高度与左子树的高度一致。 则说明左子树是,一棵满二叉树。左子树的节点数可以用公式求解。只需要再对右子树继续进行递归折半。
3. 如果此高度与左子树的高度不一致。 则说明右子树,是一棵满二叉树。右子树的节点数可以用公式求解。然后再对左子树进行递归折半。
在leetcode上实际执行时间为96ms。
class Solution {
public:
int countNodes(TreeNode* root) {
return count(root, height(root));
}
int count(TreeNode* root, int level) {
if (!root) return 0;
int rightH = height(root->right);
if (rightH == level-1)
return (1 << level) + count(root->right, level-1);
else
return (1 << level-1) + count(root->left, level-1);
}
int height(TreeNode* root) {
int level = -1;
while (root) {
++level;
root = root->left;
}
return level;
}
};
最后附上自己的第一版算法,留作纪念
在leetcode上实际执行时间为120ms。
基本思路,基于折半。
同时,关注点,在于对最后一层的节点数的统计。代码中,count是统计最后一层的节点数。
每一层递归中,统计当前子树,最下节点,是否达到指定的高度。
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) return 0;
if (!root->left) return 1;
int total = 0;
int nodes = 1;
int level = 1;
TreeNode *p = root;
while (p->left) {
total += nodes;
p = p->left;
nodes <<= 1;
++level;
}
return total + count(root, nodes, level);
}
int count(TreeNode* root, int last_level_nodes, int level) {
if (is_complete(root, level))
return last_level_nodes;
last_level_nodes >>= 1;
--level;
int total = 0;
if (root->left)
total = count(root->left, last_level_nodes, level);
if (total == last_level_nodes && root->right)
total += count(root->right, last_level_nodes, level);
return total;
}
bool is_complete(TreeNode* root, int level) {
while (root && level) {
root = root->right;
--level;
}
return !root && !level;
}
};