题目:
输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。输出节点值之和与输入整数相等的所有路径。
当访问到某一结点时,把该结点添加到路径上,并累加当前结点的值。如果当前结点为叶结点并且当前路径的和刚好等于输入的整数,则当前的路径符合要求,我们把它打印出来。解题思路:
如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到父结点。
因此我们在函数退出之前要在路径上删除当前结点并减去当前结点的值,以确保返回父结点时路径刚好是根结点到父结点的路径。
保存路径的数据结构实际上是一个栈结构,因为路径要与递归调用状态一致,而递归调用本质就是一个压栈和出栈的过程。
#include<iostream>
#include<vector>
using namespace std;
struct BinaryTreeNode
{
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
BinaryTreeNode *CreatBT();
void addTreeNode(BinaryTreeNode *&TreeNode,int value);
void FindPath(BinaryTreeNode *TreeNode,int ExpectedSum,vector<int> &path, int ¤tSum, bool &flag);
int main()
{
BinaryTreeNode *root=NULL;
int i=0, ExpectedSum=62,currentSum=0;
bool flag=false;
vector<int> path;
// addTreeNode(root,10);
// addTreeNode(root,5);
// addTreeNode(root,5);
// addTreeNode(root,4);
cout<<"二叉树的建立,以输入0表示结束。"<<endl;
cout<<"请输入根结点:"<<endl;
root=CreatBT();
cout<<"二叉树成功建立。"<<endl;
FindPath(root, ExpectedSum, path, currentSum, flag);
if(!flag)
cout<<"There is no such path, whose sum equals the ExpectedSum:"<<ExpectedSum<<endl;
system("pause");
return 0;
}
/*****************************************************************************/
//创建二叉树
BinaryTreeNode *CreatBT()
{
BinaryTreeNode *t;
int x;
cin>>x;
if(x==0)
t=NULL;
else
{
t=(BinaryTreeNode*)malloc(sizeof(BinaryTreeNode));
t->value=x;
cout<<"请输入"<<t->value<<"结点的左子结点"<<endl;
t->left=CreatBT();
cout<<"请输入"<<t->value<<"结点的右子结点"<<endl;
t->right=CreatBT();
}
return t;
}
//按照二元查找树添加结点(二元查找树,值相同的结点存于右子树)
//void addTreeNode(BinaryTreeNode *&TreeNode,int value)
//{
// if(TreeNode==NULL)
// {
// BinaryTreeNode *tempNode=new BinaryTreeNode();
// tempNode->value=value;
// tempNode->left=NULL;
// tempNode->right=NULL;
// TreeNode=tempNode;
// }
// else if(TreeNode->value > value)
// addTreeNode(TreeNode->left,value);
// else
// addTreeNode(TreeNode->right,value);
//}
/*****************************************************************************/
//TreeNode: a node
//path: a path from root to current node
//flag: test whether there is a path, whose sum equals the ExpectedSum
void FindPath(BinaryTreeNode *TreeNode,int ExpectedSum,vector<int> &path, int ¤tSum, bool &flag)
{
if(TreeNode==NULL)
return;
currentSum+=TreeNode->value;
path.push_back(TreeNode->value);
// if the node is a leaf, and the sum is same as ExpectedSum
// print the path
if(TreeNode->left==NULL && TreeNode->right==NULL && currentSum==ExpectedSum)
{
for(vector<int>::iterator it=path.begin();it!=path.end();++it)
cout<<*it<<"\t";
cout<<endl;
flag=true;
}
// if the node is not a leaf, goto its children
if(TreeNode->left)
FindPath(TreeNode->left, ExpectedSum,path,currentSum,flag);
if(TreeNode->right)
FindPath(TreeNode->right, ExpectedSum,path,currentSum,flag);
// when we finish visiting a node and return to its parent node,
// we should delete this node from the path and minus the node's value from the current sum
currentSum-=TreeNode->value;
path.pop_back();
}