Question: enter an integer and a binary tree. Access from the root node of the tree to all the nodes that the leaf node passes through to form a path. Print all paths equal to the input integer.
For example, enter the integer 22 and the following Binary Tree
10
/
5 12
/
4 7
The following two paths are printed: 10, 12, 10, 5, and 7.
Think about how to find out all the paths and then sum them to solve the problem. But for this question, some paths can be rejected before they are completely found ...... Therefore, pruning is required.
Using recursive thinking: For node 10, we only need to find the path 12 in the left and right subtree of node 10, so we can get the result soon. Note, we need to record the path.
Below isCode:
View code Void Binarytree: findpath (binarytreenode * Root, Int Va, Vector < Int > & Path)
{
If (Root = Null)
Return ;
Path. push_back (Root -> M_nvalue );
Int Value = VA - Root -> M_nvalue;
If (Value = 0 )
{
If (Root -> M_pleft = Null | Root -> M_pright = 0 )
{
For (Vector < Int > : Iterator it = Path. Begin (); it ! = Path. End (); it ++ )
Cout <* It < ' ' ;
Cout < Endl;
}
Path. pop_back ();
Return ;
}
If (Value < 0 )
Return ;
If (Root -> M_pleft)
Findpath (Root -> M_pleft, value, PATH );
If (Root -> M_pright)
Findpath (Root -> M_pright, value, PATH );
Path. pop_back ();
}