题目

方法一
年轻人不将武德,直接DFS遍历求解,但是没有用到题目完全二叉树的性质!!
class Solution {
public:
int count = 0;
int depth_max = 0;
int countNodes(TreeNode* root) {
DFS(root);
return count;
}
void DFS(TreeNode* root){
if(root == NULL){
return;
}
count++;
DFS(root->left);
DFS(root->right);
}
};
方法二
利用上完全二叉树的性质:
对左右子树分别求左向最大深度,若ldepth等于rdepth,说明左边是满二叉树,可以直接求解左子树的总数(1<<ldepth),这样相当于我们可以断定左子树没有缺结点,无需再递归左边了!同理,若ldepth大于(不等于)rdepth的话,说明右边是满二叉树,可以直接求解右子树的总和;
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL)
return 0;
int ldepth = get_depth(root->left);
int rdepth = get_depth(root->right);
if(ldepth == rdepth)
return (1<<ldepth) + countNodes(root->right);
else
return (1<<rdepth) + countNodes(root->left);
}
int get_depth(TreeNode* p){
int depth = 0;
while(p!=NULL){
depth++;
p = p->left;
}
return depth;
}
};
该博客探讨了两种方法来计算完全二叉树的节点数。方法一是直接使用深度优先搜索(DFS),但未充分利用完全二叉树的特性。方法二是利用完全二叉树的性质,通过比较左右子树的深度,优化计算过程,减少递归次数。这种方法在某些情况下能更高效地得出答案。
952

被折叠的 条评论
为什么被折叠?



