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]]
Problem Solving Ideas:
The Dfs,java is implemented as follows:
static public list<list<integer>> pathsum (TreeNode root, int sum) {list<list<integer>> List = New Arraylist<list<integer>> (); List<integer> alist = new arraylist<integer> (); if (root! = null) Dfs (alist,list, root, sum); return list;} public static void Dfs (list<integer> alist,list<list<integer>> List, TreeNode root, int sum) {if (root. left = = NULL && Root.right = = null) {if (sum = = Root.val) {alist.add (root.val); List.add (New ARRAYLIST<INTEGER&G t; (alist)); Alist.remove (Alist.size ()-1);} return;} Alist.add (Root.val), if (root.left = = null) DFS (alist,list, root.right, sum-root.val), else if (root.right = null) DFS (Ali St,list, Root.left, sum-root.val); else {list<integer> alistcopy = new Arraylist<integer> (alist);d FS (alist , list, root.right, Sum-root.val), Alist=alistcopy;dfs (Alist,list, Root.left, Sum-root.val);}}
Java for Leetcode 113 Path Sum II