二叉樹中和為某一值得所有路徑
阿新 • • 發佈:2018-12-24
問題描述:給定一顆二叉樹,求其中和為某一特定值得所有路徑。路徑定義為根到葉子的所有節點。
主要思路:採用先序遍歷的遞迴方式,利用vector儲存路徑中的節點。需要注意的就是遞迴返回時要減去vector裡面最後一個節點值,並移除節點。
測試程式碼:
#include<bits/stdc++.h> using namespace std; const int maxn=1e5+5; typedef struct node { struct node *lchild,*rchild; int val; }node,*BiTree; BiTree Create(BiTree &T)//先序建立二叉樹 { int val; scanf("%d",&val); if(val==0) T=NULL; else { T=(BiTree) malloc(sizeof(node)); T->val=val; Create(T->lchild); Create(T->rchild); } return T; } void Pre(BiTree T)//中序輸出 { if(T==NULL) return; Pre(T->lchild); printf("%d->",T->val); Pre(T->rchild); } void FindPath(BiTree T,int sum,vector<int>path,int ans)//查詢和為sum的所有路徑 { if(T==NULL) return; ans+=T->val;//加入結點值並將結點加入vector中 path.push_back(T->val); if(sum==ans&&T->lchild==NULL&&T->rchild==NULL)//判斷到達葉子節點並且路徑和為給定值 { vector<int>::iterator it;//vector迭代器定義,不想這樣也可以直接用auto需要C++11支援 for(it=path.begin();it!=path.end();it++) printf("%d ",*it); printf("\n"); } if(T->lchild) FindPath(T->lchild,sum,path,ans); if(T->rchild) FindPath(T->rchild,sum,path,ans); ans-=path.back();//返回上一個節點時需要減去最後一個結點值並將其從vector中移除 path.pop_back(); } int main() { int sum,ans=0; vector<int>path; cout<<"請按照先序遍歷輸入二叉樹結點值:"<<endl; BiTree T; T=Create(T); cout<<"中序輸出二叉樹序列:"<<endl; Pre(T); cout<<endl; cout<<"請輸入路徑和:"<<endl; scanf("%d",&sum); FindPath(T,sum,path,ans); } //測試資料:15 6 8 0 0 0 3 3 0 0 0 21