在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
#include<iostream>
using namespace std;
struct TreeNode
{
int value;
struct TreeNode* lchild;
struct TreeNode* rchild;
};
typedef struct TreeNode * Tree;
void print(TreeNode* &root,int data);
//给二叉排序树插入节点;
void InsertNode(Tree &root,int data)
{
if(root==NULL)
{
root=new TreeNode;
root->value=data;
root->lchild=root->rchild=NULL;
}
else
{
if(data>root->value)
InsertNode(root->rchild,data);
else
InsertNode(root->lchild,data);
}
}
void MidTraver(TreeNode* &root)
{
if(root->lchild!=NULL)
MidTraver(root->lchild);
if(root!=NULL)
cout<<root->value<<"\t";
if(root->rchild!=NULL)
MidTraver(root->rchild);
}
//采用中序遍历,遍历到当前节点,计算从根路径到当前路径的路径和CurrWeight=beforeweight+croot->value,计算完之后有以下几种情况:
//1.CurrWeight>constweight(指定路径和),直接返回,不论是否到叶子节点
//2.CurrWeight==constweight,分情况 A、此节点为也叶子节点,直接输出路径, B、非叶子节点,直接退出。
//3.CurrWeight<constweight,分情况处理 A、此节点为叶子节点直接返回。 B、非叶子节点,分别遍历左、右非空节点。
//----------------------------------------------------------------------------------------------------------------------
//参数说明:
//root:要遍历的树的根节点,方便从根遍历到指定叶子节点,输出指定路径。
//croot:记录当前遍历的节点地址。
//beforeweight:从根节点到croot父节点的路径之和。
//constweight:指定路径和。
//----------------------------------------------------------------------------------------------------------------------
void FindPath(TreeNode* &root,TreeNode* &croot,int beforeweight,const int constweight)
{
int CurrWeight=beforeweight;
if(croot!=NULL)//非空节点
{
CurrWeight=croot->value+beforeweight;
if(CurrWeight>constweight)
return;
}
if(CurrWeight==constweight)
{
if(croot->lchild==NULL&&croot->rchild==NULL)//叶子节点,路径和符合要求
{
cout<<"符合要求路径:"<<endl;
print(root,croot->value);
}
else
{
return;
}
}
else//CurrWeight<constweight
{
if(croot->lchild!=NULL||croot->rchild!=NULL)
{
if(croot->lchild!=NULL)
FindPath(root,croot->lchild,CurrWeight,constweight);
if(croot->rchild!=NULL)
FindPath(root,croot->rchild,CurrWeight,constweight);
}
else
return;
}
}
void print(TreeNode* &root,int data)
{
if(root!=NULL)
{
if(root->value==data)
{
cout<<root->value<<endl;
return;
}
else
{
cout<<root->value<<"->";
if(data>root->value)
print(root->rchild,data);
else
print(root->lchild,data);
}
}
}
int main()
{
Tree root=NULL;
int x;
cin>>x;
while(x!=0)
{
InsertNode(root,x);
cin>>x;
}
cout<<"this tree middle treavel sequeue is :"<<endl;
MidTraver(root);
cout<<endl<<"please input the sum of path :"<<endl;
cin>>x;
FindPath(root,root,0,x);
system("pause");
return EXIT_SUCCESS;
}
此代码完全个人创作,可直接Ctrl+C、Ctrl+V直接调试。欢迎大家转载、拍砖!谢谢~~