Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and
Sum = 22
,
5/4 8 // 11 13 4 // 7 2 5 1
Return
[,], [,]
Given a binary tree and a number sum, the output tree contains all paths from the root node to the leaf node and the path equal to sum.
Each node passing through the path records the node value to the temp variable,Using sum to subtract this node is worth a new sum value, and using this new sum value to process non-empty left and right subtree of the node, when the node is a leaf node and sum is equal to the node value, it indicates that the end node of the path and the node passing through the path is exactly equal to sum. At this time, the records temp are recorded in the result array res.
During the processing, the temp and res variables are passed by reference, saving time for parameter copying. Because it is a reference transfer, after the node executes the push_back operation on temp and recursively calls the function on its left and right subtree with non-null values, it needs to perform the pop_back operation on temp to clear the node values it has filled in, in this way, the processing of subsequent programs will not be affected.
AC code:
/*** Definition for binary tree * struct treenode {* int val; * treenode * left; * treenode * right; * treenode (int x): Val (x ), left (null), right (null) {}*}; */class solution {public: vector <int> pathsum (treenode * root, int sum) {vector <int> temp; vector <int> res; helper (root, sum, temp, Res); Return res;} void helper (treenode * root, int sum, vector <int> & temp, vector <int> & Res) {If (root = NULL) return; If (root-> left = NULL & root-> right = NULL & sum = root-> Val) {temp. push_back (root-> Val); Res. push_back (temp); temp. pop_back (); return;} If (root-> left! = NULL) {temp. push_back (root-> Val); helper (root-> left, Sum-root-> Val, temp, Res); temp. pop_back ();} If (root-> right! = NULL) {temp. push_back (root-> Val); helper (root-> right, Sum-root-> Val, temp, Res); temp. pop_back ();}}};