113. Path Sum II

Description

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 and sum = 22,

tree

return

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

Solution

DFS

在leaf节点处就要停止递归了哦。

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

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,030评论 0 10
  • Given a binary tree and a sum, find all root-to-leaf path...
    DrunkPian0阅读 252评论 0 0
  • Given a binary tree and a sum, find all root-to-leaf path...
    matrxyz阅读 187评论 0 0
  • Given a binary tree and a sum, find all root-to-leaf path...
    Jeanz阅读 196评论 0 0
  • 树上的月亮 亮弯弯的挂在那 照亮着城市的角落 关上了晚安的灯 合上疲惫的眼睛 书上的月亮 城市的灯光像流水一样 悄...
    过街的猫阅读 379评论 0 8

友情链接更多精彩内容