Simple DFS Java Solution without Helper Method


  • 0
    M
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> rs = new LinkedList<List<Integer>>();
            
            if (root == null) {
                return rs;
            }
            
            if (root.left == null && root.right == null && root.val == sum) {
                List<Integer> list = new LinkedList<Integer>();
                list.add(root.val);
                rs.add(list);
            }
            
            List<List<Integer>> rsLeft = pathSum(root.left, sum - root.val);
            for (List<Integer> list : rsLeft) {
                list.add(0, root.val);
            }
            List<List<Integer>> rsRight = pathSum(root.right, sum - root.val);
            for (List<Integer> list : rsRight) {
                list.add(0, root.val);
            }
            
            rs.addAll(rsLeft);
            rs.addAll(rsRight);
            
            return rs;
        }
        
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.