dfs using stack


  • 0
    F
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> result = new ArrayList<>();
            dfs(root, sum, result, new Stack<>());
            return result;
        }
    
        private int currentSum = 0;
    
        private void dfs(TreeNode root, int sum, List<List<Integer>> result, Stack<Integer> stack) {
            if (root == null) {
                return;
            }
            currentSum += root.val;
            stack.push(root.val);
            if (root.left == null && root.right == null && currentSum == sum) {
                result.add(new ArrayList<>(stack));
            } else {
                dfs(root.left, sum, result, stack);
                dfs(root.right, sum, result, stack);
            }
            currentSum -= root.val;
            stack.pop();
        }

Log in to reply
 

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