Title:
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]]
Test Instructions:
Given a binary tree and a sum, find all the paths of the node values from the root node to the leaf node in the Traverse and equal to the given target value.
Like what:
Given the following two-fork tree and sum = 22 ,
5 / 4 8 / / / 4 / \ / 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
Algorithm Analysis:
* Similar to the title "Path Sum"
* Also using recursive strategies
* The difference is that the subject needs to log the path of the search while traversing Dfs
* But it's important to Note that the cleanup works when recursion comes back up.
AC Code:
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; TreeNode (int x) {val = x;} *} */public class Solution {public arraylist<arraylist<integer>> pathsum (Tr Eenode root, int sum) {arraylist<arraylist<integer>> res=new arraylist<arraylist<integer>> (); Helper (Root,sum,new arraylist<integer> (), res); return res; } public void Helper (TreeNode root,int sum,arraylist<integer> cur,arraylist<arraylist<integer>> Res ) {if (root==null) return; Reach the leaf node and the root node value equals sum if (root.left==null && root.right==null && root.val==sum) {CU R.add (Root.val); Res.add (New arraylist<integer> (cur)); Clear Operation Cur.remove (Cur.size ()-1); Return }//does not reach the leaf node, the left subtree is not empty if (root.left!=null) {cur.add (root.val); Recursive call Helper (root.left,sum-root.val,cur,res) for Zuozi; On return, clear Operation Cur.remove (Cur.size ()-1); }//does not reach the leaf node, the right subtree is not empty if (root.right!=null) {cur.add (root.val); Recursive call Helper (root.right,sum-root.val,cur,res) for right subtree; On return, clear Operation Cur.remove (Cur.size ()-1); } }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Path Sum II