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.