lint0376. Binary Tree Path Sum

  • 对应LeetCode 113. Path Sum II
    打印出所有从根到叶子的路径和等于target的路径
    Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    private void helper(TreeNode root,ArrayList path,
                        int sum,int target,List> ret){
        if(root.left==null && root.right==null){
            if(sum == target)
                ret.add(new ArrayList(path));
        }
        if(root.left!=null){
            path.add(root.left.val);
            helper(root.left,path,sum+root.left.val,target,ret);
            path.remove(path.size()-1);
        }
        if(root.right!=null){
            path.add(root.right.val);
            helper(root.right,path,sum+root.right.val,target,ret);
            path.remove(path.size()-1);
        }
    }
    public List> binaryTreePathSum(TreeNode root, int target) {
        // Algorithm: Preorder Traverse
        List> ret = new ArrayList<>();
        if(root==null)
            return ret;
        ArrayList path = new ArrayList();
        path.add(root.val);
        helper(root, path, root.val, target, ret);
        return ret;
    }
}

你可能感兴趣的:(lint0376. Binary Tree Path Sum)