题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。
例如输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
思路十分简单,深搜,在每点判断和是否为22且当前节点是否为叶子节点,这题的精髓在于用一个vector容器存储路径,每次满足条件就输出一次路径,然后再pop出当前节点值,vector这一容器可看成是全局变量,这pop的过程是理解深搜递归的关键。代码中顺便把二叉树的建立又复习了一遍。
#include<stdio.h>
#include<vector>
#include<iostream>
typedef struct node
{
int m_value;
node *m_pLeft;
node *m_pRight;
}BTree;
void initBTree(BTree *T,int value)
{
T->m_value=value;
T->m_pLeft=NULL;
T->m_pRight=NULL;
}
bool InsertBTree(node *&T,int value)
{
if(T==NULL)
{
T=new node;
T->m_value=value;
T->m_pLeft=NULL;
T->m_pRight=NULL;
return true;
}
if(T->m_value==value)
{
printf("already exist");
return false;
}
if(T->m_value>value)
return InsertBTree(T->m_pLeft,value);
return InsertBTree(T->m_pRight,value);
}
void TraveBTree(BTree *T)
{
if(T)
{
TraveBTree(T->m_pLeft);
printf("%d ",T->m_value);
TraveBTree(T->m_pRight);
}
}
void Find_path(int expectsum,int &presentsum,BTree *T,std::vector<int> &path)
{
if(T)
presentsum+=T->m_value;
path.push_back(T->m_value);
bool isleaft(T->m_pLeft==NULL && T->m_pRight==NULL);
if(presentsum==expectsum && isleaft)
{
for(std::vector<int>::iterator iter=path.begin();iter!=path.end();iter++)
{
std::cout<<*iter<<' ';
}
std::cout<<std::endl;
}
if(T->m_pLeft)
{
Find_path(expectsum,presentsum,T->m_pLeft,path);
}
if(T->m_pRight)
{
Find_path(expectsum,presentsum,T->m_pRight,path);
}
path.pop_back();
presentsum-=T->m_value;
}
int main()
{
int m,i;
std::vector<int> path;
node *p;
p=NULL;
for(i=0;i<5;i++)
{
scanf("%d",&m);
InsertBTree(p,m);
}
int expectsum=22;
int presentsum=0;
Find_path(expectsum,presentsum,p,path);
system("pause");
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。