#include<iostream>
#include<stack>
#include<vector>
using namespace std;
struct BinaryTreeNode{
int m_value;
BinaryTreeNode* m_pleft;
BinaryTreeNode* m_pright;
};
void find(BinaryTreeNode* pRoot,int expectedsum){
if(pRoot == NULL) return ;
vector<int> path;
int currentsum = 0;
findpath(pRoot,expectedsum,path,currentsum);
}
//pRoot根节点, expectedsum希望得到的和,path 为双重堆栈,currentsum为当前路径的和
void findpath(BinaryTreeNode* pRoot,int expectedsum,vector<int> &path,int currentsum){
currentsum +=pRoot->m_value;
path.push_back(pRoot->m_value);
//如果当前节点为叶节点
if(pRoot->m_pleft==NULL&&pRoot->m_pright==NULL&¤tsum == expectedsum){
//打印路径
vector<int>::iterator iter = path.begin();//iterator迭代器
while(iter!=path.end()){
cout<<*iter<<endl;
}
}
//如果不是叶节点
if(pRoot->m_pleft!=NULL) Findpath(pRoot->m_pleft,expectedsum,path,currentsum);
if(pRoot->m_pright!=NULL) Findpath(pRoot->m_pright,expectedsum,path,currentsum);
//删除该路径上的节点
path.pop_back();
}
二叉树中和为某一值的路径
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.