题目来源
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.
给一个完整二叉树,求节点数目。
最直观的方法就是遍历,例如用深度优先遍历,代码如下:
/**
* 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) {
int l = 0;
TreeNode *cur = root;
int res = 0;
if (root)
dfs(root, res);
return res;
}
void dfs(TreeNode* node, int &count)
{
if (node)
count++;
else
return;
dfs(node->left, count);
dfs(node->right, count);
}
};
没错,又TLE了。想想除了最后一层,其他的都可以直接算出来,因为是满的,但是最后一层的节点数目应该怎么算呢?
没有什么特别直观的想法。
看了下答案,主要是这么一个类似的剪枝过程,就是假如是满二叉树就直接算,不是的话就看左右子树的情况,递归。
/**
* 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) {
TreeNode *l = root, *r = root;
int hl = 0, hr = 0;
while (l) {
hl++;
l = l->left;
}
while (r) {
hr++;
r = r->right;
}
return (hl == hr) ? (pow(2, hl) - 1) : (1 + countNodes(root->left) + countNodes(root->right));
}
};