求二叉树叶子节点的个数

题目描述:求二叉树叶子节点的个数

分析如下:

1.如果root 为NULL,返回0;
2.如果只有一个结点,返回1;
3.返回左右孩子叶子节点的和;


代码如下:

//#include<iostream>
//#include<queue>
//using namespace std;
//struct Node
//{
//	Node(int val)
//		:_left(NULL)
//		,_right(NULL)
//		,_val(val)
//	{}
//	Node* _left;
//	Node* _right;
//	int _val;
//};
//class BinaryTree
//{
//
//public:
//	BinaryTree()
//	{}
//	~BinaryTree()
//	{}
	
		
int IsLeafNode_count (Node* root)//统计叶子节点的个数
	{
		if(root==NULL)
			return 0;
		static int count=0;
		IsLeafNode_count (root->_left);//求左孩子的叶子节点个数
	       IsLeafNode_count (root->_right );//求右孩子的叶子结点个数
		if(root->_left ==NULL&&root->_right ==NULL)
		{
			count++;
		}
		return count;
	}

*/
//private:
//	Node* root;
//};
//void test1()
//{
//	BinaryTree t;
//	Node* node1=new Node(1);
//	Node* node2=new Node(2);
//	Node* node3=new Node(3);
//	Node* node4=new Node(4);
//	Node* node5=new Node(5);
//	Node* node6=new Node(6);
//	Node* node7=new Node(7);
//
//	node1->_left=node2;
//	node1->_right=node3;
//	node2->_left=node4;
//	node2->_right=node5;
//	node3->_left=node6;
//	node3->_right=node7;
//	//int count=t.IsLeafNode_count (node1);
//	//cout<<count<<endl;
//	int num=t.klevel_node(node1,2);
//	cout<<num<<endl;
//
//}
//int main()
//{
//	test1();
//	system("pause");
//	return 0;
//}



运行结果:



附加一个小题:

一个数组中有一个数字的次数超过了数组的一半,求出这个字符。如:int a[]={2,3,2,2,2,2,2,5,4,1,2,3},求出超过一半的数字是2

代码如下:

//#include<iostream>
//#include<assert.h>
//using namespace std;
//int half_Numbers(int *arr,int len)//数组中出现次数超过一半的数字
//{
//	assert(arr);
//	int i=0;
//	int res[12]={0};
//	while(i<len)
//	{
//		res[arr[i]]+=1;
//		i++;
//	}
//	i=0;
//	while(i<len)
//	{
//		if(res[i]>len/2)
//			return i;
//		else
//			i++;
//	}
//	return 0;
//}
//
//int main()
//{
//	int arr[]={2,3,2,2,2,2,2,5,4,1,2,3};
//	int len = sizeof(arr)/sizeof(arr[0]);
//	int num=half_Numbers(arr,len);
//	cout<<num<<endl;
//	system("pause");
//	return 0;
//}


运行结果:


猜你喜欢

转载自blog.csdn.net/wodeqingtian1234/article/details/75909334
今日推荐