C++算法之 求二叉树第k层的节点的个树

思路:

如果树为空或者k< 1,那么节点个数为0;

如果k=1,那么节点个数为1;

如果k>1,那么第k层 总节点的个数等于 左子树k-1层的节点个数+右子树k-1层节点的个数+1

代码如下:

// BTNumOfKLevel.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;



class BTree
{
public:
	int     m_nValue;
	BTree*  m_pLeft;
	BTree*  m_pRight;

	BTree(int m):m_nValue(m)
	{
		m_pLeft = m_pRight = NULL;
	}

};
//二叉树的插入实现
void Insert(int value, BTree* &root)
{
	if (root == NULL)
	{
		root = new BTree(value);
	}
	else if(value < root->m_nValue)
		Insert(value,root->m_pLeft);
	else if(value > root->m_nValue)
		Insert(value,root->m_pRight);
	else
		;
}

int GetNumOfKthLevel(BTree* root, int k)
{
	if(root == NULL || k < 1)
		return 0;
	if(k == 1)
		return 1;
	int LeftNum = GetNumOfKthLevel(root->m_pLeft,k-1);
	int RightNum = GetNumOfKthLevel(root->m_pRight,k-1);

	int ret = LeftNum+RightNum;
	return ret;
}

int _tmain(int argc, _TCHAR* argv[])
{
	BTree* m_pRoot = new BTree(4);
	Insert(3,m_pRoot);
	Insert(6,m_pRoot);
	Insert(1,m_pRoot);
	Insert(2,m_pRoot);
	Insert(5,m_pRoot);
	Insert(8,m_pRoot);
	Insert(7,m_pRoot);
	Insert(10,m_pRoot);

	int number = GetNumOfKthLevel(m_pRoot,4);
	cout<<"第4层上的节点的个数为:"<<number<<endl;




	getchar();
	return 0;
}


 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值