[Leetcode 113] Path Sum (Medium)

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1
Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

Solution: Top down (find all paths which adds up is equal to target sum)

/**
 * 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>> result = new ArrayList<> ();
        
        if (root == null) {
            return result;
        }
        
        List<Integer> path = new ArrayList<> ();
        
        pathSumHelper (root, path, result, sum);
        
        return result;
    }
    
    private void pathSumHelper (TreeNode root, List<Integer> path, List<List<Integer>> result, int sum) {
        if (root == null) {
            return;
        }
        
        if (root.left == null && root.right == null && root.val == sum) {
            path.add (root.val);
            result.add (new ArrayList<> (path));
            path.remove (path.size () - 1);
            return;
        } else if (root.left == null && root.right == null && root.val != sum) {
            return;
        }
        
        int newSum = sum - root.val;
        path.add (root.val);
        
        pathSumHelper (root.left, path, result, newSum);
        pathSumHelper (root.right, path, result, newSum);
        
        path.remove (path.size () - 1);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,974评论 0 10
  • 今天打完了IOS系统上的仙剑DOS复刻版。这不是我第一次通关仙一,上次也是在苹果设备上运行复刻版。不过上一次用了修...
    连看客都不是阅读 469评论 0 0
  • 人是生而自由的 但却无往不在枷锁之中 自以为是其他的一切的主人的人 反而比其他一切更是奴隶 ”生理上的、性格的、情...
    silvincent阅读 739评论 0 9

友情链接更多精彩内容