二叉树操作——查找,获取二叉树中节点的个数 (两种方式)、求二叉树的高度 、获取二叉数中叶子节点的个数 、获取二叉树第K层节点的个数

结构体:

typedef char BTDataType;

typedef struct BTNode
{
	struct BTNode* pLeft;
	struct BTNode* pRight;
	BTDataType data;
}BTNode;

查找:

二叉树结点中所有的 value 都不重复
找结点的 value 是 v 的结点
如果找到了,返回 v 所在的结点地址
如果没找到,返回 NULL
Find 返回 NULL 意味着没找到,返回 非 NULL,意味着找到了
先确定根结点 -> 左子树中是否包含 -> 右子树中是否包含
如果根结点就是,不需要再去左右子树查找了
如果左子树找到了,不需要去右子树找了

BTNode * Find(BTNode *pRoot, int v) {
	if (pRoot == NULL) {
		return NULL;
	}

	// 先去根找
	if (pRoot->data == v) {
		// 找到了
		return pRoot;
	}
	// 如果根没找到,去左子树找
	BTNode *result = Find(pRoot->pLeft, v);
	if (result != NULL) {
		// 左子树里找到了
		return result;
	}

	// 如果左子树没找到,去右子树找
	result = Find(pRoot->pRight, v);
	if (result != NULL) {
		return result;
	}
	else {
		return NULL;
	}
}

获取二叉树中节点的个数(两种方式) :

// 获取二叉树中节点的个数 
int GetNodeCount(BTNode* pRoot) //遍历方式
{
	if (pRoot == NULL)
		return;

	int size;
	size++;

	GetNodeCount(pRoot->pLeft);
	GetNodeCount(pRoot->pRight);

	return size;
}


int GetNodeCount2(BTNode *pRoot)   // 递推的方式
{
	if (pRoot == NULL) 
	{
		return 0;
	}

	int left = GetNodeCount2(pRoot->pLeft);
	int right = GetNodeCount2(pRoot->pRight);

	return left + right + 1;
}

求二叉树高度:

// 求二叉树的高度 
int Height(BTNode* pRoot)
{
	if (pRoot == NULL)
		return;

	int left = Height(pRoot->pLeft);
	int right = Height(pRoot->pRight);

	return (left < right ? right: left)+1;
}

获取二叉数中叶子节点的个数:

// 获取二叉数中叶子节点的个数 
int GetLeafNodeCount(BTNode* pRoot)
{
	if (pRoot == NULL) 
	{
		return 0;
	}

	if (pRoot->pLeft == NULL&&pRoot->pRight == NULL)
		return 1;

	int left=GetLeafNodeCount(pRoot->pLeft);
	int right=GetLeafNodeCount(pRoot->pRight);

	return left + right + 1;
}

获取二叉树第K层节点的个数:

步骤
如果空树 为0
如果不为空 第一层为1
求第K层 可以先求一左树的k - 1层 + 右树的k - 1层
直到每次执行到一个根的 第一层返回1, 如果没有的话返回0

int GetKLevelNodeCount(BTNode* pRoot, int K)
{
	
	if (pRoot == NULL) 
	{
		return 0;
	}

	if (K == 1)
	{	// 隐含的前提是, root != NULL
		return 1;
	}

	return GetKLevelNodeCount(pRoot->pLeft, K - 1)
		+ GetKLevelNodeCount(pRoot->pRight, K - 1);
	

}

猜你喜欢

转载自blog.csdn.net/qq_42659468/article/details/89485678
今日推荐