A sword is an offer---a binary tree and a path to a value.

Source: Internet
Author: User

Title: Two fork in tree and path to a value

Requirement: Enter a binary tree with a node and an integer to print out all the paths of the node value in the two-fork tree and the input integer. A path is defined as a path from the root node of the tree down to the node through which the leaf nodes go.

1 /*2 struct TreeNode {3 int val;4 struct TreeNode *left;5 struct TreeNode *right;6 TreeNode (int x):7 val (x), left (null), right (null) {8     }9 };*/Ten classSolution { One  Public: Avector<vector<int> > Findpath (treenode* root,intExpectnumber) { -  -     } the};

Problem Solving Code:

1 /*2 struct TreeNode {3 int val;4 struct TreeNode *left;5 struct TreeNode *right;6 TreeNode (int x):7 val (x), left (null), right (null) {8     }9 };*/Ten classSolution { One  Public: Avector<vector<int> > Findpath (treenode* root,intExpectnumber) { -vector<vector<int> >Res; -vector<int>path; the         intCurrentsum =0; -         if(Root = =NULL) -             returnRes; - Search (root, Expectnumber, path, res, currentsum); +         returnRes; -     } +  A     voidSearch (treenode* proot,intExpectnumber, vector<int> &Path, atvector<vector<int> > &res,intcurrentsum) { -  -Currentsum + = proot->Val; -Path.push_back (proot->val); -  -         BOOLIsLeaf = Proot->left = = NULL && Proot->right = =NULL; in         //  -         if(Currentsum = = Expectnumber &&isleaf) { to res.push_back (path); + Path.pop_back (); -             return ; the         } *         // $         if(Proot->left! =NULL)Panax NotoginsengSearch (proot->Left , Expectnumber, Path, res, currentsum); -         if(Proot->right! =NULL) theSearch (proot->Right , Expectnumber, Path, res, currentsum); + Path.pop_back (); A     } the};

Time is limited, first put the answer here, there is time to come back to add details.

A sword is an offer---a binary tree and a path to a value.

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.