链式二叉树统计结点个数的方法和bug

方法一:

分治:分而治之

cpp 复制代码
int BTreeSize1(BTNode* root)
{
	if (root == NULL) return 0;
	else return BTreeSize(root->left)+BTreeSize(root->right)+1;
}

方法二:

遍历计数:设置一个计数器,对二叉树正常访问,访问到一个结点就让这个计数器++。应要求,我们应该设置一个static静态变量。

cpp 复制代码
int BTreeSize2(BTNode* root)
{
	static int size = 0;
	if (root == NULL) return size;
	else size++;
	BTreeSize2(root->left);
	BTreeSize2(root->right);
	return size;
}

下面对这两种方法进行验证。

创建一个二叉树:

cpp 复制代码
typedef int BTDataType;
typedef struct BinaryTreeNode
{
	BTDataType data;
	struct BinaryTreeNode* left;
	struct BinaryTreeNode* right;
}BTNode;
BTNode* BuyNode(BTDataType x)
{
	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	if (node == NULL)
	{
		perror("malloc fail::");
		return;
	}
	node->data = x;
	node->left = NULL;
	node->right = NULL;
	return node;
}
BTNode* CreatBinaryTree()
{
	BTNode* node1 = BuyNode(1);
	BTNode* node2 = BuyNode(2);
	BTNode* node3 = BuyNode(3);
	BTNode* node4 = BuyNode(4);
	BTNode* node5 = BuyNode(5);
	BTNode* node6 = BuyNode(6);

	node1->left = node2;
	node1->right = node4;
	node2->left = node3;
	node4->left = node5;
	node4->right = node6;
	return node1;
}

验证代码:

cpp 复制代码
int main() 
{
	BTNode* root = CreatBinaryTree();
	printf("%d\n", BTreeSize1(root));
	printf("%d\n", BTreeSize2(root));
	return 0;
}

验证结果正确。

但是,方法二里面仍然存在一些问题。

static静态变量size,在此函数中,理论上是一个局部变量,但是其生命周期却是全局变量。

所以,这就会导致多次访问此函数时,出现累加现象:

运行结果:

从而导致结果不准确。

而且,因为其为局部变量,无法在函数调用后,在函数外部手动置零,继而产生无法修补的大坑。

结论:方法二不可行!

如果真要实现方法二这种思路,则应设置全局变量,然后每次计算完成后,手动置零。

cpp 复制代码
int size = 0;
void BTreeSize2(BTNode* root)
{
	if (root == NULL) return;
	else size++;
	BTreeSize2(root->left);
	BTreeSize2(root->right);
	return;
}
int main()
{
    BTNode* root = CreatBinaryTree();
	BTreeSize2(root);
	printf("%d\n",size);
	size = 0;
	BTreeSize2(root);
	printf("%d\n", size);
	size = 0;
	BTreeSize2(root);
	printf("%d\n", size);
	return 0;
}

验证结果正确:

相关推荐
m0_547486663 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr3 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_33 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.3 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.3 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣3 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9923 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
淡海水4 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1014 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
2401_839080544 天前
C++常见八股
数据结构·c++·算法