您的位置:首页 > 其它

在二元树中查找和为某一值的所有路径

2010-08-11 14:25 309 查看
#include <iostream>
#include <vector>
using namespace std;

struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};

int count=0; //print control

void FindPath(
BinaryTreeNode* pTreeNode,
int expectedSum,
vector<int>& path,
int& currentSum)
{
if (!pTreeNode)
{
return;
}

currentSum+=pTreeNode->m_nValue;
path.push_back(pTreeNode->m_nValue);

bool isLeaf=!(pTreeNode->m_pLeft)&&!(pTreeNode->m_pRight);

if (currentSum==expectedSum && isLeaf)
{
vector<int>::iterator iter;
for (iter=path.begin(); iter!=path.end(); iter++)
{
cout<<*iter<<'\t';
}
cout<<endl;
}

if (pTreeNode->m_pLeft)
{
FindPath(pTreeNode->m_pLeft, expectedSum, path, currentSum);
}
if (pTreeNode->m_pRight)
{
FindPath(pTreeNode->m_pRight, expectedSum, path, currentSum);
}

//when finish visiting a node and return to its parent node,
//should delete this node from the path and
//minus the node's value from the current sum
currentSum-=pTreeNode->m_nValue;
path.pop_back();
}

void AddTree(BinaryTreeNode** T, int num)
{
if (*T==NULL)
{
*T=(BinaryTreeNode*)malloc(sizeof(BinaryTreeNode));
(*T)->m_nValue=num;
(*T)->m_pLeft=NULL;
(*T)->m_pRight=NULL;
}
else if ((*T)->m_nValue>num)
{
AddTree(&((*T)->m_pLeft), num);
}
else
{
AddTree(&((*T)->m_pRight), num);
}
}

void MidTraversal(BinaryTreeNode* T)
{
if(T!=NULL)
{
MidTraversal(T->m_pLeft);
count++;
if (count%5==0)
{
cout<<T->m_nValue<<endl;
}
else
{
cout<<T->m_nValue<<"\t";
}

MidTraversal(T->m_pRight);
}
}

int main()
{
BinaryTreeNode* T=NULL;

AddTree(&T, 10);
AddTree(&T, 12);
AddTree(&T, 5);
AddTree(&T, 7);
AddTree(&T, 4);

cout<<"Mid reversal tree is:\n";
MidTraversal(T);

vector<int> path;
int sum=0;
FindPath(T, 22, path, sum);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: