Find all k-sum paths in a binary tree

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












Description:



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.



Leetcode



Code:



class Solution 
private List<List<Integer>> paths = new ArrayList<>();

public List<List<Integer>> pathSum(TreeNode root, int sum)
traverse(root, sum, new ArrayList<Integer>());
return paths;


private void traverse(TreeNode root, int sum, ArrayList<Integer> path)
if (root != null)
path.add(root.val);

if (root.left == null && root.right == null && sum == root.val)
paths.add((ArrayList) path.clone());


traverse(root.left, sum - root.val, path);
traverse(root.right, sum - root.val, path);

path.remove(path.size() - 1);









share|improve this question

























    up vote
    2
    down vote

    favorite












    Description:



    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.



    Leetcode



    Code:



    class Solution 
    private List<List<Integer>> paths = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int sum)
    traverse(root, sum, new ArrayList<Integer>());
    return paths;


    private void traverse(TreeNode root, int sum, ArrayList<Integer> path)
    if (root != null)
    path.add(root.val);

    if (root.left == null && root.right == null && sum == root.val)
    paths.add((ArrayList) path.clone());


    traverse(root.left, sum - root.val, path);
    traverse(root.right, sum - root.val, path);

    path.remove(path.size() - 1);









    share|improve this question





















      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      Description:



      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.



      Leetcode



      Code:



      class Solution 
      private List<List<Integer>> paths = new ArrayList<>();

      public List<List<Integer>> pathSum(TreeNode root, int sum)
      traverse(root, sum, new ArrayList<Integer>());
      return paths;


      private void traverse(TreeNode root, int sum, ArrayList<Integer> path)
      if (root != null)
      path.add(root.val);

      if (root.left == null && root.right == null && sum == root.val)
      paths.add((ArrayList) path.clone());


      traverse(root.left, sum - root.val, path);
      traverse(root.right, sum - root.val, path);

      path.remove(path.size() - 1);









      share|improve this question











      Description:



      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.



      Leetcode



      Code:



      class Solution 
      private List<List<Integer>> paths = new ArrayList<>();

      public List<List<Integer>> pathSum(TreeNode root, int sum)
      traverse(root, sum, new ArrayList<Integer>());
      return paths;


      private void traverse(TreeNode root, int sum, ArrayList<Integer> path)
      if (root != null)
      path.add(root.val);

      if (root.left == null && root.right == null && sum == root.val)
      paths.add((ArrayList) path.clone());


      traverse(root.left, sum - root.val, path);
      traverse(root.right, sum - root.val, path);

      path.remove(path.size() - 1);











      share|improve this question










      share|improve this question




      share|improve this question









      asked Jun 24 at 13:02









      CodeYogi

      1,99932060




      1,99932060




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          It's a fine solution. I have a few minor comments.



          • It's easy to overlook that pathSum doesn't clear the content of paths, which will affect the returned value from subsequent calls, which is likely to be unexpected by callers. In this online puzzle it doesn't seem to matter, but I think it's better to avoid any possible confusion.


          • The clone with the cast is ugly. The .clone() method except on arrays is a bit controversial, with questionable benefits if any. I suggest to avoid it. You can replace it with a nice clean paths.add(new ArrayList<>(path))


          • The signature of traverse would be better to use List instead of ArrayList.


          • I would use an early return in traverse, to have less indented code.






          share|improve this answer





















            Your Answer




            StackExchange.ifUsing("editor", function ()
            return StackExchange.using("mathjaxEditing", function ()
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            );
            );
            , "mathjax-editing");

            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "196"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: false,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );








             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f197161%2ffind-all-k-sum-paths-in-a-binary-tree%23new-answer', 'question_page');

            );

            Post as a guest






























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            It's a fine solution. I have a few minor comments.



            • It's easy to overlook that pathSum doesn't clear the content of paths, which will affect the returned value from subsequent calls, which is likely to be unexpected by callers. In this online puzzle it doesn't seem to matter, but I think it's better to avoid any possible confusion.


            • The clone with the cast is ugly. The .clone() method except on arrays is a bit controversial, with questionable benefits if any. I suggest to avoid it. You can replace it with a nice clean paths.add(new ArrayList<>(path))


            • The signature of traverse would be better to use List instead of ArrayList.


            • I would use an early return in traverse, to have less indented code.






            share|improve this answer

























              up vote
              1
              down vote



              accepted










              It's a fine solution. I have a few minor comments.



              • It's easy to overlook that pathSum doesn't clear the content of paths, which will affect the returned value from subsequent calls, which is likely to be unexpected by callers. In this online puzzle it doesn't seem to matter, but I think it's better to avoid any possible confusion.


              • The clone with the cast is ugly. The .clone() method except on arrays is a bit controversial, with questionable benefits if any. I suggest to avoid it. You can replace it with a nice clean paths.add(new ArrayList<>(path))


              • The signature of traverse would be better to use List instead of ArrayList.


              • I would use an early return in traverse, to have less indented code.






              share|improve this answer























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                It's a fine solution. I have a few minor comments.



                • It's easy to overlook that pathSum doesn't clear the content of paths, which will affect the returned value from subsequent calls, which is likely to be unexpected by callers. In this online puzzle it doesn't seem to matter, but I think it's better to avoid any possible confusion.


                • The clone with the cast is ugly. The .clone() method except on arrays is a bit controversial, with questionable benefits if any. I suggest to avoid it. You can replace it with a nice clean paths.add(new ArrayList<>(path))


                • The signature of traverse would be better to use List instead of ArrayList.


                • I would use an early return in traverse, to have less indented code.






                share|improve this answer













                It's a fine solution. I have a few minor comments.



                • It's easy to overlook that pathSum doesn't clear the content of paths, which will affect the returned value from subsequent calls, which is likely to be unexpected by callers. In this online puzzle it doesn't seem to matter, but I think it's better to avoid any possible confusion.


                • The clone with the cast is ugly. The .clone() method except on arrays is a bit controversial, with questionable benefits if any. I suggest to avoid it. You can replace it with a nice clean paths.add(new ArrayList<>(path))


                • The signature of traverse would be better to use List instead of ArrayList.


                • I would use an early return in traverse, to have less indented code.







                share|improve this answer













                share|improve this answer



                share|improve this answer











                answered Jun 26 at 19:40









                janos

                95.3k12119342




                95.3k12119342






















                     

                    draft saved


                    draft discarded


























                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f197161%2ffind-all-k-sum-paths-in-a-binary-tree%23new-answer', 'question_page');

                    );

                    Post as a guest













































































                    Popular posts from this blog

                    Greedy Best First Search implementation in Rust

                    Function to Return a JSON Like Objects Using VBA Collections and Arrays

                    C++11 CLH Lock Implementation