See a face in the morning with the path sum very much like, give a TreeNode root and a target, find a path from the root node to the leaf, where each node and equals target. Unlike path sum, path sum requires a Boolean return, which is slightly altered to return the path. The principle is the same
Public classSolution { PublicList<integer> getpathsum (TreeNode root,inttarget) {List<Integer> res =NewArraylist<>(); if(Root = =NULL) { returnRes; } getpathsum (res, root, target); returnRes; } Private BooleanGetpathsum (list<integer> res, TreeNode root,inttarget) { if(Root = =NULL) { return false; } res.add (Root.val); Target-=Root.val; if(Root.left = =NULL&& Root.right = =NULL&& target = = 0) { return true; } if(Getpathsum (res, root.left, target)) {return true; } if(Getpathsum (res, root.right, target)) {return true; } res.remove (Res.size ()-1); return false; }}
Variant of Path sum