美文网首页
113. Path Sum II

113. Path Sum II

作者: 衣介书生 | 来源:发表于2018-04-05 15:23 被阅读6次

    题目分析

    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,

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

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

    代码

    /**
     * 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 ArrayList<>();
            ArrayList<Integer> path = new ArrayList<>();
            if(root == null) {
                return paths;
            }
            helper(root, sum, path, paths);
            return paths;
        }
        public void helper(TreeNode root, int sum, List<Integer> path, List<List<Integer>> paths) {
            // 判断是不是叶子结点
            if(root == null) {
                return;
            }
            sum -= root.val;
            path.add(root.val);
            if(root.left == null && root.right == null) {
                if(0 == sum) { 
                    paths.add(new ArrayList<Integer>(path));
                }
            } else {
                if(root.left != null) helper(root.left, sum, path, paths);
                if(root.right != null) helper(root.right, sum, path, paths);
            }
            path.remove(path.size() - 1);
        }
    }
    

    相关文章

      网友评论

          本文标题:113. Path Sum II

          本文链接:https://www.haomeiwen.com/subject/rcgpcftx.html