您的位置:首页 > 其它

打印从根节点到二叉树中指定值节点的路径

2014-04-21 12:55 337 查看
// Tree.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include
#include
using namespace std;
struct Note
{
Note*left;
Note*right;
int value;
};
int count=0;
vector m_p;
int GetAndPrint(Note*root,int n)
{
if(root==NULL)
{
return 0;
}
if(root&&root->value!=n)
{
m_p.push_back(root);
}
if(root->value==n)
{
count++;
m_p.push_back(root);
vector::iterator it=m_p.begin();
for(;it!=m_p.end();it++)
{
cout<<(*it)->value;

}
cout<<endl;
m_p.pop_back();
return 1;

}

if(root->left==NULL&&root->right==NULL)
{
m_p.pop_back();
bool is=false;
vector::iterator it=m_p.begin();
for(;it!=m_p.end();it++)
{
if((*it)->value==n)
is=true;

}
if(is==false)
{

cout<<"NotFound"<<endl;
return 0;
}
if(is==true)
{
return 1;
}
}
int isp2=GetAndPrint(root->left,n);
int isp1=GetAndPrint(root->right,n);
if(0==isp1&&0==isp2)
{
m_p.pop_back();
return 0;

}

}
int _tmain(int argc, _TCHAR* argv[])
{
//cout<<"请输入几个节点的数字"<< endl;

int n=0;
//n>>n;

Note *note1=new Note();
Note *note2=new Note();
Note *note3=new Note();
Note *note4=new Note();
Note *note5=new Note();
Note *note6=new Note();
Note *note7=new Note();
Note *note8=new Note();
Note *note9=new Note();
Note *note10=new Note();

note1->value=2;
note2->value=3;
note3->value=4;

note4->value=5;
note5->value=6;
note6->value=7;

note7->value=2;
note8->value=3;
note9->value=4; ;;
note10->value=5;

note1->left=note2;
note1->right=note3;

note2->left=note4;
note2->right=note5;

note3->left=note6;
note3->right=note7;

note4->left=note8;
note4->right=note9;

note5->left=note10;

GetAndPrint(note1,7);
if(count==0)
return 0;
if(count==1)
return 1;
if(count>=2)
return 2;

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