日月流转,朝夕变换,我们的生活不是那过去的好时光,不是未来的乌托邦,而是现实本身! ——摘自 奥格。曼狄诺《羊皮卷》
4.在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如输入整数22 和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12 和10, 5, 7。
#include <assert.h>
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
typedef struct BTreeNode
{
BTreeNode* Leftchild;
BTreeNode* Rightchild;
int Value;
}Tnode,*Tree;
void addTree(Tree& T, int num)
{
if(T == NULL)
{
T = (BTreeNode *)malloc(sizeof(Tnode));
T->Value = num;
T->Leftchild = NULL;
T->Rightchild = NULL;
return;
}
else if(T->Value > num)
{
addTree((T->Leftchild), num);
}
else if(T->Value < num)
{
addTree((T->Rightchild), num);
}
else
{
cout << "重复加入同一结点" << endl;
}
}
void findPath( Tree pNode, int expectedSum, vector<int>& path,int& currentSum)
{
assert(pNode!=NULL);
currentSum += pNode->Value;
path.push_back(pNode->Value);
bool isLeaf = !(pNode->Leftchild) && !(pNode->Rightchild);/*判断是否为叶子节点*/
if(currentSum == expectedSum && isLeaf)
{
vector<int>::iterator iter;
for(iter = path.begin(); iter != path.end(); iter++)
{
cout << *iter << "\t";
}
cout << endl;
}
if(pNode->Leftchild!=NULL)
findPath(pNode->Leftchild, expectedSum, path, currentSum);
if(pNode->Rightchild!=NULL)
findPath(pNode->Rightchild, expectedSum, path, currentSum);
currentSum -= pNode->Value;
path.pop_back();
}
int main()
{
Tree T = NULL;
vector<int> path;
int sum = 0;
addTree(T, 10);
addTree(T, 12);
addTree(T, 5);
addTree(T, 7);
addTree(T, 4);
findPath(T, 22, path, sum);
return 0;
}
1431

被折叠的 条评论
为什么被折叠?



