Example: A path with a sum of 22
Evaluation steps
rule: When a node is accessed by a pre-order traversal, we add the node to the path and accumulate the value of the node, if the node is a leaf node and the value of the node in the path is exactly equal to the input integer, then the current path meets the requirements and we print it out. If the current node is not a leaf node, it continues to access its child nodes. The recursive function automatically returns to its parent node after the current node access is complete. So we want to delete the current node on the path before the function exits, and subtract the value of the current node to ensure that the path is exactly the path from the root node to the parent node when the parent node is returned. It is not difficult to see that the data structure of a saved path is actually a stack, because the path is consistent with the recursive invocation state, and the nature of the recursive invocation is the process of compacting and stacking.
However, because the use of the stack is not easy to output the path, so the vector can be push_back and pop_back in the tail and delete the path node
The
code is as follows:
Voidfindpath
(
Binarytreenode* Proot,
int Expectedsum,
std::vector<int>& Path,
int& Currentsum
)
{
Currentsum + = proot->m_nvalue;
Path.push_back (Proot->m_nvalue);
// if it is a leaf node, and the sum of the nodes on the path equals the input value
// print out this path
BOOL IsLeaf = Proot->m_pleft = = null&& Proot->m_pright = = NULL;
if (currentsum = = Expectedsum &&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 it is not a leaf node, it traverses its child nodes .
if (proot->m_pleft! = NULL)
Findpath (proot->m_pleft,expectedsum, Path, currentsum);
if (proot->m_pright! = NULL)
Findpath (proot->m_pright,expectedsum, Path, currentsum);
// deletes the current node on the path before returning to the parent node .
// and subtract the value of the current node in the Currentsum .
Currentsum-= proot->m_nvalue;
Path.pop_back ();
}
Voidcallfindpath (binarytreenode* proot, int expectedsum)
{
if (Proot = = NULL)
Return
Std::vector<int> path;
int currentsum = 0;
Findpath (Proot, Expectedsum, path,currentsum);
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
5:2 Fork in the tree and for a path that has been