4.在二叉树中找出和为某一值的所有路径
题目: 输入一个二叉树,从根结点开始往下访问一直到叶子节点所经过的所有节点组成一条路径,打印出和与输入整数相等的所有路径
解: 参考打印二叉树中某节点的祖先节点 http://www.cnblogs.com/buxianghe/p/3198662.html
这里还是采用后续非递归遍历的方法,记录在栈中的节点元素的和,当1个节点2次进栈2次出栈时,并且满足从根结点到它的和等于输入的和,并且它是叶子节点时,那么此时栈中元素就是这条路径,打印它
代码:
/* 参考后续遍历 */ #include<iostream> using namespace std; typedef struct node { int data; struct node* left; struct node* right; }Tree; typedef struct { Tree* point; int count; }Node; #define MAX 100 typedef struct { Node data[MAX]; int top; }Stack; Stack* create_stack(void) { Stack* s=new Stack; if(s) s->top=-1; return s; } void free_stack(Stack* s) { if(s) delete s; } bool empty_stack(Stack* s) { if(s->top==-1) return true; return false; } bool full_stack(Stack* s) { if(s->top==MAX-1) return true; return false; } void push_stack(Stack* s,Node value) { if(full_stack(s)) return ; s->top++; (s->data[s->top]).point=value.point; (s->data[s->top]).count=value.count; } void pop_stack(Stack* s,Node* value) { if(empty_stack(s)) return ; (*value).point=(s->data[s->top]).point; (*value).count=(s->data[s->top]).count; s->top--; } void get_stack(Stack* s,Node* value) { if(empty_stack(s)) return ; (*value).point=(s->data[s->top]).point; (*value).count=(s->data[s->top]).count; } Tree* create_tree(void) { int data; Tree* t=NULL; cin>>data; if(data==0) return NULL; else { t=new Tree; t->data=data; t->left=create_tree(); t->right=create_tree(); } } void free_tree(Tree* t) { if(t) { free_tree(t->left); free_tree(t->right); delete t; t=NULL; } } void preorder(Tree* t) { if(t) { preorder(t->left); preorder(t->right); cout<<t->data<<" "; } } void pre_dopath(Tree* t,int sum) { Tree* p=t; Stack *s1,*s2; Node temp_node; s1=create_stack(); s2=create_stack(); int stack_sum=0; while(p || !empty_stack(s1)) { if(p) { stack_sum+=p->data; temp_node.point=p; temp_node.count=0; push_stack(s1,temp_node); p=p->left; } else // { pop_stack(s1,&temp_node); p=temp_node.point; stack_sum-=p->data; if(temp_node.count==0) { temp_node.count=1; push_stack(s1,temp_node); stack_sum+=p->data; p=p->right; } else //该出栈了这个元素 { if(p->left==NULL && p->right==NULL && (p->data+stack_sum==sum)) { cout<<p->data<<" "; while(!empty_stack(s1)) { pop_stack(s1,&temp_node); cout<<(temp_node.point)->data<<" "; push_stack(s2,temp_node); } while(!empty_stack(s2)) { pop_stack(s2,&temp_node); push_stack(s1,temp_node); } cout<<endl; } p=NULL; } } } free_stack(s1); free_stack(s2); } int main(void) { Tree *t=NULL; int sum; cin>>sum; t=create_tree(); pre_dopath(t,sum); free_tree(t); }
输入给定的测试树,输入和22,输入是10 5 4 0 0 7 0 0 12 0 0 ,此时打印2条路径(从底往上打印,也可从商往下打印)12 10和7 5 10。