给定二叉树和一个整数,打印所有路径和为输入整数的路径,路径是根节点到叶节点算一条路径
用回溯法遍历所有路径,每到一个节累加该节点值
如果累计值等于对应整数,则直接打印
如果累计值大于,则回退
如果累计值小于,继续往下
直至结束
如果节点中有负值,就要遍历所有的节点;如果都为正数,可以回溯
void FindPath_1(BinaryTreeNode* pNode, int expectedSum,int addNum,std::list<BinaryTreeNode*>& ilist)//diy
{
if (pNode->m_nValue + addNum == expectedSum)
{
if (pNode->m_pLeft != nullptr || pNode->m_pRight != nullptr)
return;
ilist.push_back(pNode);
for (auto& it : ilist)
printf("%d,", it->m_nValue);
printf("\n");
}
else if (pNode->m_nValue + addNum < expectedSum)
{
ilist.push_back(pNode);
addNum += pNode->m_nValue;
if (pNode->m_pLeft != nullptr)
FindPath_1(pNode->m_pLeft, expectedSum, addNum, ilist);
if (pNode->m_pRight != nullptr)
FindPath_1(pNode->m_pRight, expectedSum, addNum, ilist);
}
else
return;
ilist.pop_back();
return;
}
void FindPath_1(BinaryTreeNode* pRoot,int expectedSum)//diy
{
if (pRoot == nullptr) return;
std::list<BinaryTreeNode*> nodelist;
return FindPath_1(pRoot, expectedSum, 0, nodelist);
}