Find all root to leaf paths in 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
1
down vote

favorite












Description:



Given a binary tree, return all root-to-leaf paths.



Leetcode




/**
* Definition for a binary tree node.
* public class TreeNode
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) val = x;
*
*/



Code:



class Solution 

public List<String> binaryTreePaths(TreeNode root)
List<String> paths = new ArrayList<>();
traverse(root, new ArrayList<>(), paths);
return paths;


private void traverse(TreeNode root, List<String> path, List<String> paths)
if (root == null) return;

path.add(""+root.val);
if (root.left == null && root.right == null)
paths.add(String.join("->", path));


traverse(root.left, path, paths);
traverse(root.right, path, paths);

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








share|improve this question



























    up vote
    1
    down vote

    favorite












    Description:



    Given a binary tree, return all root-to-leaf paths.



    Leetcode




    /**
    * Definition for a binary tree node.
    * public class TreeNode
    * int val;
    * TreeNode left;
    * TreeNode right;
    * TreeNode(int x) val = x;
    *
    */



    Code:



    class Solution 

    public List<String> binaryTreePaths(TreeNode root)
    List<String> paths = new ArrayList<>();
    traverse(root, new ArrayList<>(), paths);
    return paths;


    private void traverse(TreeNode root, List<String> path, List<String> paths)
    if (root == null) return;

    path.add(""+root.val);
    if (root.left == null && root.right == null)
    paths.add(String.join("->", path));


    traverse(root.left, path, paths);
    traverse(root.right, path, paths);

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








    share|improve this question























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      Description:



      Given a binary tree, return all root-to-leaf paths.



      Leetcode




      /**
      * Definition for a binary tree node.
      * public class TreeNode
      * int val;
      * TreeNode left;
      * TreeNode right;
      * TreeNode(int x) val = x;
      *
      */



      Code:



      class Solution 

      public List<String> binaryTreePaths(TreeNode root)
      List<String> paths = new ArrayList<>();
      traverse(root, new ArrayList<>(), paths);
      return paths;


      private void traverse(TreeNode root, List<String> path, List<String> paths)
      if (root == null) return;

      path.add(""+root.val);
      if (root.left == null && root.right == null)
      paths.add(String.join("->", path));


      traverse(root.left, path, paths);
      traverse(root.right, path, paths);

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








      share|improve this question













      Description:



      Given a binary tree, return all root-to-leaf paths.



      Leetcode




      /**
      * Definition for a binary tree node.
      * public class TreeNode
      * int val;
      * TreeNode left;
      * TreeNode right;
      * TreeNode(int x) val = x;
      *
      */



      Code:



      class Solution 

      public List<String> binaryTreePaths(TreeNode root)
      List<String> paths = new ArrayList<>();
      traverse(root, new ArrayList<>(), paths);
      return paths;


      private void traverse(TreeNode root, List<String> path, List<String> paths)
      if (root == null) return;

      path.add(""+root.val);
      if (root.left == null && root.right == null)
      paths.add(String.join("->", path));


      traverse(root.left, path, paths);
      traverse(root.right, path, paths);

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










      share|improve this question












      share|improve this question




      share|improve this question








      edited Jun 26 at 21:39









      Mast

      7,32663484




      7,32663484









      asked Jun 26 at 20:04









      CodeYogi

      1,99932060




      1,99932060




















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          It's a fine solution.
          Tracking the values on the path,
          growing and shrinking while traversing to the leafs,
          finally adding a concatenated values is natural and easy to understand.



          An alternative (and not necessarily better) approach that may perform better is to reduce the string creation, concatenation by replacing the List<String> for path with a StringBuilder, something like:



          int length = sb.length();
          sb.append("->").append(root.val);

          if (root.left == null && root.right == null)
          paths.add(sb.substring(2));


          traverse(root.left, sb, paths);
          traverse(root.right, sb, paths);

          sb.setLength(length);


          This might be premature optimization, and "clever" code.
          I think your original is fine as is.






          share|improve this answer





















          • I thought about it too but went with the generic approach. Also, I am finding this pattern very easy to understand.
            – CodeYogi
            Jun 26 at 21:49

















          up vote
          4
          down vote













          regarding the translation from int to String



          path.add(""+root.val);


          This is both unclear and also involves unnecessary String creation. Why not use the "official" conversion method? it clearly states the intention and is more efficient



          path.add(String.valueOf(root.val));





          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%2f197308%2ffind-all-root-to-leaf-paths-in-binary-tree%23new-answer', 'question_page');

            );

            Post as a guest






























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            It's a fine solution.
            Tracking the values on the path,
            growing and shrinking while traversing to the leafs,
            finally adding a concatenated values is natural and easy to understand.



            An alternative (and not necessarily better) approach that may perform better is to reduce the string creation, concatenation by replacing the List<String> for path with a StringBuilder, something like:



            int length = sb.length();
            sb.append("->").append(root.val);

            if (root.left == null && root.right == null)
            paths.add(sb.substring(2));


            traverse(root.left, sb, paths);
            traverse(root.right, sb, paths);

            sb.setLength(length);


            This might be premature optimization, and "clever" code.
            I think your original is fine as is.






            share|improve this answer





















            • I thought about it too but went with the generic approach. Also, I am finding this pattern very easy to understand.
              – CodeYogi
              Jun 26 at 21:49














            up vote
            1
            down vote



            accepted










            It's a fine solution.
            Tracking the values on the path,
            growing and shrinking while traversing to the leafs,
            finally adding a concatenated values is natural and easy to understand.



            An alternative (and not necessarily better) approach that may perform better is to reduce the string creation, concatenation by replacing the List<String> for path with a StringBuilder, something like:



            int length = sb.length();
            sb.append("->").append(root.val);

            if (root.left == null && root.right == null)
            paths.add(sb.substring(2));


            traverse(root.left, sb, paths);
            traverse(root.right, sb, paths);

            sb.setLength(length);


            This might be premature optimization, and "clever" code.
            I think your original is fine as is.






            share|improve this answer





















            • I thought about it too but went with the generic approach. Also, I am finding this pattern very easy to understand.
              – CodeYogi
              Jun 26 at 21:49












            up vote
            1
            down vote



            accepted







            up vote
            1
            down vote



            accepted






            It's a fine solution.
            Tracking the values on the path,
            growing and shrinking while traversing to the leafs,
            finally adding a concatenated values is natural and easy to understand.



            An alternative (and not necessarily better) approach that may perform better is to reduce the string creation, concatenation by replacing the List<String> for path with a StringBuilder, something like:



            int length = sb.length();
            sb.append("->").append(root.val);

            if (root.left == null && root.right == null)
            paths.add(sb.substring(2));


            traverse(root.left, sb, paths);
            traverse(root.right, sb, paths);

            sb.setLength(length);


            This might be premature optimization, and "clever" code.
            I think your original is fine as is.






            share|improve this answer













            It's a fine solution.
            Tracking the values on the path,
            growing and shrinking while traversing to the leafs,
            finally adding a concatenated values is natural and easy to understand.



            An alternative (and not necessarily better) approach that may perform better is to reduce the string creation, concatenation by replacing the List<String> for path with a StringBuilder, something like:



            int length = sb.length();
            sb.append("->").append(root.val);

            if (root.left == null && root.right == null)
            paths.add(sb.substring(2));


            traverse(root.left, sb, paths);
            traverse(root.right, sb, paths);

            sb.setLength(length);


            This might be premature optimization, and "clever" code.
            I think your original is fine as is.







            share|improve this answer













            share|improve this answer



            share|improve this answer











            answered Jun 26 at 21:16









            janos

            95.3k12119342




            95.3k12119342











            • I thought about it too but went with the generic approach. Also, I am finding this pattern very easy to understand.
              – CodeYogi
              Jun 26 at 21:49
















            • I thought about it too but went with the generic approach. Also, I am finding this pattern very easy to understand.
              – CodeYogi
              Jun 26 at 21:49















            I thought about it too but went with the generic approach. Also, I am finding this pattern very easy to understand.
            – CodeYogi
            Jun 26 at 21:49




            I thought about it too but went with the generic approach. Also, I am finding this pattern very easy to understand.
            – CodeYogi
            Jun 26 at 21:49












            up vote
            4
            down vote













            regarding the translation from int to String



            path.add(""+root.val);


            This is both unclear and also involves unnecessary String creation. Why not use the "official" conversion method? it clearly states the intention and is more efficient



            path.add(String.valueOf(root.val));





            share|improve this answer

























              up vote
              4
              down vote













              regarding the translation from int to String



              path.add(""+root.val);


              This is both unclear and also involves unnecessary String creation. Why not use the "official" conversion method? it clearly states the intention and is more efficient



              path.add(String.valueOf(root.val));





              share|improve this answer























                up vote
                4
                down vote










                up vote
                4
                down vote









                regarding the translation from int to String



                path.add(""+root.val);


                This is both unclear and also involves unnecessary String creation. Why not use the "official" conversion method? it clearly states the intention and is more efficient



                path.add(String.valueOf(root.val));





                share|improve this answer













                regarding the translation from int to String



                path.add(""+root.val);


                This is both unclear and also involves unnecessary String creation. Why not use the "official" conversion method? it clearly states the intention and is more efficient



                path.add(String.valueOf(root.val));






                share|improve this answer













                share|improve this answer



                share|improve this answer











                answered Jun 27 at 6:47









                Sharon Ben Asher

                2,038512




                2,038512






















                     

                    draft saved


                    draft discarded


























                     


                    draft saved


                    draft discarded














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

                    );

                    Post as a guest













































































                    Popular posts from this blog

                    Python Lists

                    Aion

                    JavaScript Array Iteration Methods