100 question _ 04 find all paths for a value in the binary tree

Source: Internet
Author: User
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 ();
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.