在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
算法思想:
用回溯法,先序遍历树,当遍历到普通非叶子节点时,将该节点加入路径,递归遍历左子树和右子树。当遍历到叶子节点时,如果累加值为目标值,输出路径,然后回溯,否则直接回溯(回溯包括恢复路径,即从路径中删除本结点)。
#include<iostream>
#include<vector>
using namespace std;
typedef struct _tree
{
_tree(int v)
{
value = v;
pleft = NULL;
pright = NULL;
}
_tree* pleft;
_tree* pright;
int value;
}Node, *pNode;
pNode CreateTree()
{
pNode p = new Node(10);
p->pleft = new Node(5);
p->pright = new Node(12);
p->pleft->pleft = new Node(4);
p->pleft->pright = new Node(7);
return p;
}
void DestroyTree(pNode p)
{
if(p)
{
DestroyTree(p->pleft);
DestroyTree(p->pright);
delete p;
p = NULL;
}
}
bool IsLeaf(pNode p)
{
return !(p->pleft || p->pright);
}
//输出路径
void DisplayResult(const vector<int>& v)
{
vector<int>::const_iterator iter = v.begin();
for (; iter!=v.end(); ++iter)
{
cout<<*iter<<" ";
}
cout<<endl;
}
void FindPath(pNode p, int target)
{
//用于保存路径结果
static vector<int> vResult;
//空树返回
if(p==NULL)
return;
//递归进入该结点时 加上该结点值
vResult.push_back(p->value);
if(IsLeaf(p))
{ //如果是叶子节点 并且加上后刚好得到目标值 则输出路径
if(p->value == target)
DisplayResult(vResult);
}
else
{ //否则递归左子树和右子树
int nexttarget = target - p->value;
FindPath(p->pleft, nexttarget);
FindPath(p->pright, nexttarget);
}
//递归退出该结点时,还原路径
vResult.erase(vResult.end()-1);
}
void main()
{
pNode pRoot = CreateTree();
cout<<"满足条件的路径有: "<<endl;
FindPath(pRoot, 22);
DestroyTree(pRoot);
}