Description:
Given a binary tree, find all paths this sum of the nodes in the path equals to a Given number target .
A valid path is from root node to any of the leaf nodes.
Example:
Given a binary tree, and target = 5 :
1 / 2 4 / 2 3
Return
[ [1, 2, 2], [1, 4]]
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramroot the binary tree *@paramtarget an integer *@returnAll valid Paths*/ Privatelist<list<integer>> result =NewArraylist<>(); Privatearraylist<integer> Path =NewArraylist<integer>(); PublicList<list<integer>> binarytreepathsum (TreeNode root,inttarget) { //Write Your code here//Handel Corner Cases if(Root = =NULL) { returnresult; } path.add (Root.val); Helper (root, path, target-root.val); returnresult; } Private voidHelper (TreeNode node, arraylist<integer> path,inttarget) { if(Node.left = =NULL&& Node.right = =NULL) { if(target = = 0) {Result.add (NewArraylist<integer>(path)); } return; } if(Node.left! =NULL) {path.add (node.left.val); Helper (node.left, path, Target-node.left.val); Path.remove (Path.size ()-1); } if(Node.right! =NULL) {path.add (node.right.val); Helper (node.right, path, Target-node.right.val); Path.remove (Path.size ()-1); } }}View Code
With the divide and conquer method, the most important thing, the "to remove", the last value of T.left or Root.right, and also remember that if node.left = = null and Node.right = NULL, then it's time to return.
Lintcode:binary Tree Path Sum