上篇博客基本已经将二叉树的基本算法进行了简单介绍,这篇文章主要介绍二叉树中节点的查找及第K行子树个数
首先二叉树查找
需要用到递归算法
代码实现内部函数
Node* _Find(Node* root,const T& x)
{
if (root==NULL)
return NULL;
if(root->_date==x)
return root;
Node* left=_Find(root->left,x);
Node* right=_Find(root->right,x);
if(left)
{
return _Find(root->left,x);
}
if(right)
{
return _Find(root->right,x);
}
}
外部调用函数
Node* Find(const T& x)
{
return _Find(_root,x);
}
下面介绍第K曾子树个数方法
递归实现,如下
int _GetKLevel(Node* root,size_t k)
{
if(root==NULL)
return 0;
if(k==1)
return 1;
else
return _GetKLevel(root->left,k-1)+_GetKLevel(root->right,k-1);
}
外部调用函数
size_t GetKLevel(size_t k)
{
return _GetKLevel(_root,k);
}
调用方法
void test()
{
int a1[10]={1,2,3,'#','#',4,'#','#',5,6};
BinTree<int> t1(a1,10,'#');
BinTreeNode<int> *searchNode = t1.Find(3);
if(NULL == searchNode){
cout<<"没有找到该节点"<<endl;
}
else
{
cout<<searchNode->_date<< endl;
}
cout<<t1.GetKLevel(2)<<endl;
}