叶子节点的个数
size_t _GetLeefNode(Node *pRoot)
{
if (pRoot == NULL)
return 0;
if (NULL == pRoot->pLeft&&NULL == pRoot->pRight)
return 1;
return _GetLeefNode(pRoot->pLeft) + _GetLeefNode(pRoot->pRight);
}
第K层节点的个数
size_t _Height(Node *pRoot)
{
if (NULL==pRoot)
return 0;
size_t highLeft = 1+_Height(pRoot->pLeft);
size_t highRight = 1+_Height(pRoot->pRight);
return highLeft > highRight ? highLeft : highRight;
}
int GetKLevelNode(int k)
{
if (k<0 || k>_Height(_pRoot))
return -1;
return _GetKLevelNode(_pRoot, k);
}
int _GetKLevelNode(Node *pRoot, int k)
{
if (nullptr == pRoot)
return 0;
if (k == 1 )
return 1;
return _GetKLevelNode(pRoot->_pLeft, k-1)+_GetKLevelNode(pRoot->_pRight, k-1);
}
一个数组中有一个数字的次数超过了数组的一半,求出这个字符。
//如:int a[]={2,3,2,2,2,2,2,5,4,1,2,3},求出超过一半的数字是2
#include<iostream>
using namespace std;
int partion(int *arr, int left, int right)
{
int begin = left;
int end = right;
int key = arr[begin];
while (begin < end)
{
//注意快排从如果左边选比较值,则应从右边开始比较
while (begin < end&&arr[begin] >= key)
--end;
while (begin < end&&arr[begin] <= key)
++begin;
swap(arr[begin], arr[end]);
}
swap(arr[left], arr[begin]);
return begin;
}
int getNum(int *arr, int len)
{
if (nullptr == arr || len <= 0)
return -1;
int start = 0;
int end = len - 1;
int mid = start+(end-start)>>1;
int index = partion(arr, 0, end);
while (index != mid)
{
if (mid > index)
{
start = index +1;
index = partion(arr, start, end);
}
else
{
end = index -1;
index = partion(arr, start, end);
}
}
return arr[index];
}
int main()
{
int arr[] = { 2, 3, 2, 2,2, 2, 5, 4, 1, 2, 3 };
int len = sizeof(arr) / sizeof(arr[0]);
int res = getNum(arr, len);
cout << res << endl;
system("pause");
}