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 andSum = 22
,
5/4 8 // 11 13 4 // 7 2 5 1
Return
[,], [,]
Analysis: this problem can be solved using DFS. When traversing to the leaf node, determine whether the sum of the current path is equal to the target sum. If it is equal, add the current path to the result.
The Code is as follows:
1 Class Solution { 2 Public : 3 Vector <vector < Int > Pathsum (treenode * root, Int Sum ){ 4 Vector <vector < Int > Res; 5 If (! Root) Return Res; 6 Vector <Int > Path; 7 DFS (Res, path, root, 0 , Sum ); 8 Return Res; 9 } 10 Void DFS (vector < Int >>& Res, vector < Int > & Path, treenode * root,Int Pre_sum, Int Sum ){ 11 If (! Root) Return ; 12 Path. push_back (root-> Val ); 13 Int Cur_sum = pre_sum + root-> Val; 14 DFS (Res, path, root-> Left, cur_sum, sum ); 15 DFS (Res, path, root-> Right, cur_sum, sum ); 16 If (Cur_sum = sum &&! Root-> left &&! Root-> Right) res. push_back (PATH ); 17 Path. pop_back (); 18 } 19 };