Simple questions
I
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such this adding up all the values along the Path equals the given sum.
For example:
Given the below binary tree sum = 22
and,
5 / 4 8 / / / 4 / \ 7 2 1
Return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
Public classSolution { Public BooleanHaspathsum (TreeNode root,intsum) { if(root==NULL)return false; if(Root.val==sum && root.left==NULL&& root.right==NULL)return true; return(Haspathsum (Root.left, sum-root.val) | | haspathsum (root.right, sum-root.val)); }}
Ii
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]]
Typical DFS topics
Public classSolution { PublicArraylist<arraylist<integer>> pathsum (TreeNode root,intsum) {ArrayList<ArrayList<Integer>> res =NewArraylist<arraylist<integer>>(); ArrayList<Integer> cl =NewArraylist<integer>(); DFS (res, cl, root, sum); returnRes; } Private voidDFS (arraylist<arraylist<integer>> res, arraylist<integer> cl,treenode N,ints) { if(n==NULL)return; Cl.add (N.val); if(n.left==NULL&& n.right==NULL&& n.val==s) {Res.add (NewArraylist<integer> (CL));//if dont rebuild, would make conflict and the last line of Cl.remove Oh! }Else{ if(n.left!=NULL) DFS (res, cl, n.left,s-n.val); if(n.right!=NULL) DFS (res, cl, n.right,s-n.val); } cl.remove (Cl.size ()-1); }}
Path Sum I, II