输入一个整数和一颗二元树。从数的根节点开始往下访问一直到叶节点所经过的所有节点形成一条路径。打印出和输入整数相等的所有路径。
例如,输入整数20和如下二元树
10
6 14
4 8 12 16
则打印出1条路径:10,6,4
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<vector>
using namespace std;
struct BiTreeNode{
int m_nValue;
BiTreeNode *m_pLeft;
BiTreeNode *m_pRight;
};
void CreateBiTreeNode(BiTreeNode* &pCurrent,int value)
{
if(pCurrent==NULL)
{
BiTreeNode* pBiTree=new BiTreeNode();
pBiTree->m_pLeft=NULL;
pBiTree->m_pRight=NULL;
pBiTree->m_nValue=value;
pCurrent=pBiTree;
}
else
{
if((pCurrent->m_nValue)>value)
{
CreateBiTreeNode(pCurrent->m_pLeft,value);
}
else if((pCurrent->m_nValue)<value)
{
CreateBiTreeNode(pCurrent->m_pRight,value);
}
else
{
cout<<"重复加入节点"<<endl;
}
}
}
//思路一:
const int maxHeight=10;
void helper(int *path,int sum,int top,BiTreeNode* pRoot);
void printPath(int sum,BiTreeNode* pRoot)
{
int path[maxHeight]={0};
int top=0;
helper(path,sum,top,pRoot);
}
void helper(int *path,int sum,int top,BiTreeNode* pRoot)
{
if(pRoot==NULL)
{
return;
}
sum-=pRoot->m_nValue;
top=top+1;
path[top]=pRoot->m_nValue;
if(pRoot->m_pRight==NULL&&pRoot->m_pLeft==NULL)
{
if(sum==0)
{
for(int i=1;i<top+1;i++)
{
cout<<path[i]<<" "<<endl;
}
return;
}
}
helper(path,sum,top,pRoot->m_pLeft);
helper(path,sum,top,pRoot->m_pRight);
sum+=pRoot->m_nValue;
top=top-1;
}
//思路二
typedef struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
void PrintPath(BinaryTreeNode* pRoot,int expectedSum)
{
if(pRoot==NULL)
{
return;
}
vector<int> path;
int currentSum=0;
FindPath(pRoot,expectedSum,path,currentSum);
}
void FindPath(BinaryTreeNode* pRoot,int expectedSum,vector<int> &path,int currentSum)
{
currentSum+=pRoot->m_nValue;
path.push_back(pRoot->m_nValue);
//如果是叶节点,并且路径上的结点的和等于输入的值
bool isLeaf=pRoot->m_pLeft==NULL && pRoot->m_pRight;
if(isLeaf && currentSum==expectedSum)
{
cout<<"The Path is found!"<<endl;
vector<int>::iterator iter=path.begin();
for(;iter!=path.end();++iter)
{
cout<<*iter<<"\t";
}
cout<<endl;
}
//如果不是叶结点,则遍历它的子结点
if(pRoot->m_pLeft!=NULL)
{
FindPath(pRoot->m_pLeft,expectedSum,path,currentSum);
}
if(pRoot->m_pRight!=NULL)
{
FindPath(pRoot->m_pRight,expectedSum,path,currentSum);
}
path.pop_back();
}
int main()
{
BiTreeNode *pRoot=NULL;
int key=0;
CreateBiTreeNode(pRoot,10);
CreateBiTreeNode(pRoot,6);
CreateBiTreeNode(pRoot,14);
CreateBiTreeNode(pRoot,4);
CreateBiTreeNode(pRoot,8);
CreateBiTreeNode(pRoot,12);
CreateBiTreeNode(pRoot,16);
cout<<"Please input a number"<<endl;
cin>>key;
printPath(key,pRoot);
system("pause");
return 0;
}