-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffer_34
33 lines (31 loc) · 1.08 KB
/
offer_34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//面试题34:二叉树中和为某一值得路径
void FindPath(BinaryTreeNode* pRoot,int exceptedSum)
{
if(pRoot==nullptr)
return false;
std::vector<int> path;
int currentSum=0;
FindPath(pRoot,exceptedSum,path,currentSum);
}
void FindPath(BinaryTreeNode* pRoot,int exceptedSum,std::vector<int>& path,int currentSum)
{
currentSum+=pRoot->m_nValue;
path.push_back(pRoot->m_nValue);
//如果是叶节点,并且路径上节点值得和等于输入的值
//则打印出这条路径
bool isLeaf=pRoot->m_pLeft==nullptr && pRoot->m_pRight==nullptr;
if(currentSum==exceptedSum&&isLeaf){
printf("A path is found:");
std vector<int>::iterator iter=path.begin();
for(;iter!=path.end();++iter){
printf("%d\t",*iter);
}
printf("\n");
}
//如果不是叶子节点,则遍历它的子节点
if(pRoot->m_pLeft!=nullptr)
FindPath(pRoot->m_pLeft,exceptedSum,path,currentSum);
if(pRoot->m_pRight!=nullptr)
FindPath(pRoot->m_pRight,exceptedSum,path,currentSum);
path.pop_back();//在返回父节点之前,在路径上删除当前节点
}