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 value, find all the paths from the root to the leaf and the paths equal to the value.
Depth-first traversal.
Public list <integer> pathsum (treenode root, int sum) {list <integer> ret = new arraylist <list <integer> (); list <integer> List = new arraylist <integer> (); DFS (root, sum, RET, list); return ret;} public void DFS (treenode root, int sum, list <list <integer> ret, list <integer> List) {If (root = NULL) return; If (root. val = sum & root. left = NULL & root. right = NULL) {list. add (root. val); List <integer> temp = new arraylist <integer> (list); // copy a ret. add (temp); list. remove (list. size ()-1); // Delete return;} List. add (root. val); DFS (root. left, sum-root.val, RET, list); DFS (root. right, sum-root.val, RET, list); list. remove (list. size ()-1);} // definition for Binary treepublic class treenode {int val; treenode left; treenode right; treenode (int x) {val = x ;}}