1. 程式人生 > 實用技巧 >樹的演算法題學習

樹的演算法題學習

//1.計算度為2 度為1 度為0的結點個數 
void Count(BiTree bt)
{
	if(bt)
	{
		if(bt->lchild && bt->rchild) n2++;
		else if(bt->lchild && !bt->rchild || bt->rchild && !bt->lchild)
			n1++;
		else n0++;
		if(bt->lchild != nullptr) Count(bt->lchild);
		if(bt->rchild != nullptr) Count(bt->rchild);
	}
}


//2.計算葉子節點個數
int BinaryTreeLeavesCount(BiTree  root, int &count) {
	if (root != NULL && root->lchild == NULL && root->rchild == NULL) {
		count++;
	}

	if (root!=NULL) {
		BinaryTreeLeavesCount(root->lchild, count);
		BinaryTreeLeavesCount(root->rchild, count);
	}
	return count;
}


//東北大學2014年查詢值為X的結點 返回結點在樹中的層數 
int search(BiTree t,int x,int count)
{
	BiTree p;
	p = t;
	if(p == nullptr)
		return 0;
	if(x == p->data)
	{
		return count;
	}else
	{
		int l = search(p->lchild,x,count+1);
		if(l != 0)
			return l;
		else
			return search(p->rchild,x,count+1);
	}
}

//查詢小於等於X結點的個數
int count_search(BiTree t,int x)
{
	if(!t) return 0;
	if(t->data <= x)
	{
		return count_search(t->lchild,x)+count_search(t->rchild,x)+1;
	}
	else
		return count_search(t->lchild,x)+count_search(t->rchild,x);
	
}