标签:二叉树和为某值
很容易想到用先序遍历,并传递进去一个数组和当前和。just so so
代码:
#include <iostream> #include <vector> #include <assert.h> using namespace std; typedef struct tree{ int data; struct tree * lchild; struct tree * rchild; }Tree,*pTree; void createTree(pTree &pHead){ int temp; scanf("%d",&temp); if(temp){ pHead = new Tree(); pHead->data = temp; createTree(pHead->lchild); createTree(pHead->rchild); }else pHead = NULL; } void print(const pTree root){ if(root){ cout<<root->data<<" "; print(root->lchild); print(root->rchild); }else return; } void findPath(pTree p,int cursum,vector<int> vePa,int excepted){ cursum += p->data; vePa.push_back(p->data); //判断是否为叶节点 bool isleaf = (p->lchild == NULL && p->rchild == NULL); // 当为叶节点并且 等于期望值 if(isleaf && cursum == excepted){ cout<<endl << "path :"; vector<int>::iterator iter = vePa.begin(); while(iter != vePa.end()){ cout<<*iter<<" "; iter++; } } if(p->lchild != NULL){ findPath(p->lchild,cursum,vePa,excepted); } if(p->rchild != NULL) findPath(p->rchild,cursum,vePa,excepted); cursum -=p->data; vePa.pop_back(); } void findPath(pTree root,int excepted){ if(root == NULL) return ; else{ int curSum =0; vector<int> vePa; findPath(root,curSum,vePa,excepted); } } int main() { pTree pHead=NULL; createTree(pHead); print(pHead); findPath(pHead,22); return 0; }
标签:二叉树和为某值
原文地址:http://blog.csdn.net/buyingfei8888/article/details/38398159