【Data Structure & Algorithm】二叉树中和为某值的所有路径
二叉树中和为某值的所有路径
题目:输入一个整数和一个二叉树,从树的根节点开始往下访问一直到叶节点所经过的所有节点形成一条路径。打印出和与输入整数相等的所有路径。
例如输入整数22和如下二叉树:
10
/ \
5 12
/ \
4 7
则打印出两套路径:10, 12和10, 5, 7。
二叉树节点的数据结构定义为
structBinaryTreeNode
{
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
}
分析:当访问到某一节点时,把该节点添加到路径上,并累加当前节点的值。如果当前节点为叶节点并且当前路径的和刚好等于输入的整数,则当前路径符合要求,则打印出来。如果当前节点不是叶节点,则继续访问其子节点。当前节点访问结束后,递归函数将自动回到父节点。因此在函数退出之前要在路径上删除当前节点并减去当前节点的值,以保证返回父节点时路径刚好是根节点到父节点的路径。不难看出保存路径的数据结构实际上是一个栈结构,因为路径要与递归调用状态一致,而递归调用本质就是一个压栈和出栈的过程。
voidFindPath
(
BinaryTreeNode* pTreeNode,
int expecedSum,
std::vector<int>&path,
int& currentSum
)
{
if(!pTreeNode) return;
currentSum += pTreeNode -> m_nValue;
path.push_back(pTreeNOde -> m_nValue);
//if the node is a leaf, and the sum isas pre-defined,
//the path is what we want. print thepath
bool isLeaf = (!pTreeNode -> m_pLeft&& !pTreeNode -> m_pRight);
if(currentSum == expectedSum &&isLeaf)
{
std::vector<int>::iterator iter = path.begin();
for(; iter != path.end(); ++iter)
std::cout<< *iter << ‘\t’;
std::cout<< std:: endl;
}
//if the node is not a leaf, gotoits children
if(pTreeNode -> m_pLeft)
FindPath(pTreeNode-> m_pLeft, expectedSum, path, currentSum);
if(pTreeNode -> m_pRight)
FindPath(pTreeNode-> m_pRight, expectedSum, path, currentSum);
//when we finish visiting a nodeand return to its parent node,
//we should delete this node fromthe path and
//minus the node’s value from thecurrent sum
currentSum -= pTreeNode ->m_nValue;
path.pop_back();
}

浙公网安备 33010602011771号