二叉树中和为某一值的所有路径

引用编程之美,百度笔试题

 1 //二叉树中和为某一值的所有路径
 2 void findPath(treeNode* root,vector<treeNode*>& path, int& curSum,int expSum){
 3     if(root==NULL)
 4         return;
 5     //将当前节点的值放入path中(模仿栈),并将求和更新
 6     path.push_back(root);
 7     curSum=curSum+root->data;
 8     //是否为叶节点
 9     bool isLeaf=((root->lChild==NULL)&&(root->rChild==NULL));
10     //当为叶节点,且当前的和等于要求的和
11     if(isLeaf && curSum==expSum){
12         for(vector<treeNode*>::iterator it=path.begin();it!=path.end();it++)
13             cout<<*it<<" ";
14         cout<<endl;
15     }
16     //当不是叶节点,则递归左右子树
17     if(root->lChild!=NULL)
18         findPath(root->lChild,path,curSum,expSum);
19     if(root->rChild!=NULL)
20         findPath(root->rChild,path,curSum,expSum);
21     //凡是程序运行到这,说明已经到了叶节点;不管该叶节点是否在符合条件的路径上,都要从当前路径中删除该叶节点
22     path.pop_back();
23     curSum=curSum-root->data;
24     path.pop_back();
25 }

 

posted @ 2014-09-20 09:18  liuzhiminxd  阅读(157)  评论(0编辑  收藏  举报