Topic:
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 sum = 22
and,
5 / 4 8 / / / 4 / \ / 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
Ideas:
Note that you must go to leaf node
PackageTree;Importjava.util.ArrayList;Importjava.util.List; Public classPathsumii { PublicList<list<integer>> pathsum (TreeNode root,intsum) {List<List<Integer>> res =NewArraylist<list<integer>>(); if(Root = =NULL)returnRes; List<Integer> record =NewArraylist<integer>(); Pathsum (res, record, root, sum); returnRes; } Private voidPathsum (list<list<integer>> Res, list<integer> record, TreeNode root,intsum) { if(Root = =NULL&& sum! = 0)return; if(Root = =NULL&& sum = = 0) {Res.add (record); } Else { if(Root.left = =NULL|| Root.right = =NULL) {List<Integer> NewRecord =NewArraylist<integer>(record); Newrecord.add (Root.val); Pathsum (res, NewRecord, Root.left==NULL? Root.right:root.left, Sum-root.val); } Else{List<Integer> NewRecord1 =NewArraylist<integer>(record); Newrecord1.add (Root.val); Pathsum (res, newRecord1, root.left, Sum-root.val); List<Integer> NewRecord2 =NewArraylist<integer>(record); Newrecord2.add (Root.val); Pathsum (res, newRecord2, root.right, Sum-root.val); } } } }
Leetcode-path Sum II