题目:
输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径,从树的根节点开始往下一直到叶节点所经过的结点形成一条路径。
结点定义:
struct BinaryTreeNode{
int val;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
分析:
举例,如下的二叉树,二叉树和整数22,打印出两条路径,第一条:结点10,12;第二条:结点10,5,7;
按照前序遍历的顺序,遍历二叉树,把经过的路径上的结点保存下来,每访问到一个节点,就把当前的结点添加到路径中。
在使用前序遍历的方式访问某一节点时,把该节点添加到路径上,并累加节点的值,如果该节点为叶节点并且路径中节点值的和刚好等于输入的整数,则打印;如果当前节点不是叶节点,则继续访问他的子节点,如果已经到达叶节点,但不等于输入的整数值,那么返回父节点时,要在路径上删除当前节点并减去当前节点的值。
代码:
void FindPath(BinaryTreeNode *proot,int expectedSum)
{
if(proot == NULL)
return ;
std::vector<int> path;
int currentSum = 0;
FindPath(proot,expectedSum,path,currentSum );
}
void FindPath(BinaryTreeNode *proot,int expectedSum,std::vector<int>& path,
int ¤tSum )
{
currentSum += proot->val;
path.push_back(proot->val);
//如果是叶节点,并且路径上节点的和等于输入的值,打印这条路径
bool isLeaf = proot->left ==NULL && proot->right ==NULL;
if(currentSum == expectedSum && isLeaf)
{
printf("A path is found:");
std::vector<int>::iterator iter = path.begin();
for(;iter != path.end(); ++iter)
printf("%d\t",*iter);
printf("\n");
}
//不是叶节点,则遍历他的子节点
if(proot->left != NULL)
FindPath(proot->left,expectedSum ,path,currentSum );
if(proot->right != NULL)
FindPath(proot->right ,expectedSum ,path,currentSum );
//返回父节点之前,在路径上删除当前节点,并在currentSum中减去当前节点的值
currentSum -= proot->val;
path.pop_back();
}
参考《剑值offer》