//打印和为某一值的路径
template<class T> void binaryTree<T>::printPath(treeNode<T> *ptree,int path[], int sum, int top)
{
path[top++] = ptree->data;
sum-=ptree->data;
if(ptree->lchild == nullptr && ptree->rchild == nullptr) //到叶子节点
{
if(sum == 0) //找到
{
for(int i = 0; i < top; i++)
{
std::cout << path[i] << ',';
}
std::cout << std::endl;
}
}
else
{
if(ptree->lchild != nullptr)
printPath(ptree->lchild,path,sum,top); //在左子树找
if(ptree->rchild != nullptr)
printPath(ptree->rchild,path,sum,top); //在右子树找
}
top--; //还原状态
sum+=ptree->data;
}
template<class T> void binaryTree<T>::printPath(treeNode<T> *ptree,int path[], int sum, int top)
{
path[top++] = ptree->data;
sum-=ptree->data;
if(ptree->lchild == nullptr && ptree->rchild == nullptr) //到叶子节点
{
if(sum == 0) //找到
{
for(int i = 0; i < top; i++)
{
std::cout << path[i] << ',';
}
std::cout << std::endl;
}
}
else
{
if(ptree->lchild != nullptr)
printPath(ptree->lchild,path,sum,top); //在左子树找
if(ptree->rchild != nullptr)
printPath(ptree->rchild,path,sum,top); //在右子树找
}
top--; //还原状态
sum+=ptree->data;
}