#include <iostream> #include <vector> using std::endl; using std::vector; using std::cin; using std::cout; struct treeNode { int value; treeNode*left; treeNode*right; }; void Path(treeNode * root ,int exceptSum,int ¤tSum,vector<int>&path,bool &isFind) { if(root!=NULL) { currentSum+=root->value; path.push_back(root->value); if(root->left==NULL&&root->right==NULL&¤tSum==exceptSum) { for(vector<int>::size_type i =0;i!=path.size();i++) { isFind=true; cout<<path[i]<<" "; } } Path(root->left,exceptSum,currentSum,path,isFind); Path(root->right,exceptSum,currentSum,path,isFind); currentSum-=root->value; path.pop_back(); } } void findPath(treeNode* root,int exceptSum) { if(root==NULL) { cout<<"tree is NULL,no path"; return ; } bool isFind=false; vector<int>path; int currentSum=0; Path(root,exceptSum,currentSum,path,isFind); if(!isFind) { cout<<" NO PATH! "; } return ; } treeNode * treeInsert(treeNode* head,int n) { treeNode* newNode=new treeNode; newNode->left=newNode->right=NULL; newNode->value=n; if (head==NULL) { return newNode; } treeNode *head1=head,*head2=NULL; while (head1!=NULL)//先确定待插入的父亲节点 { head2=head1; if(head1->value>n) head1=head1->left; else head1=head1->right; } if(head2->value>n) { head2->left=newNode; } else { head2->right=newNode; } return head; } int getHeight(treeNode * root) { if(root==NULL) return 0; else return (getHeight(root->left)>getHeight(root->right)?getHeight(root->left):getHeight(root->right))+1; } void ByLevel(treeNode * root,int level) { if(root==NULL||level<0) return ; if (level==0) cout<<root->value<<" "; else { ByLevel(root->left,level-1); ByLevel(root->right,level-1); } } int main() { treeNode *head=NULL; head=treeInsert(head,5); head=treeInsert(head,1); head=treeInsert(head,9); head=treeInsert(head,3); head=treeInsert(head,8); head=treeInsert(head,5); int high=getHeight(head); for(int i=0;i<high;i++) { cout<<"LEVEL:"<<i+1<<endl; ByLevel(head,i); cout<<endl; cout<<"__________________"<<endl; } findPath(head,27); return 0; }
原文地址:http://blog.csdn.net/hero_zouzongling/article/details/45667459