with help of Stringbuilder 2ms runtime beats 85% java sol pls review


  • 1
     ```public class Solution {
     StringBuilder sb = new StringBuilder();
     List<String> li = new ArrayList();  
    public List<String> binaryTreePaths(TreeNode root) {
       pathCount(root,0);
       return li; 
       }
    public List<String>pathCount(TreeNode root , int len){
        if(root==null) return null;
        if(root.left!=null || root.right!=null)
        sb.append(root.val+"->");
        if(root.left==null && root.right==null) 
       {  sb.append(root.val);
          li.add(sb.toString());
          return li;
       }
        int oldlen=sb.length();           //// Very good job you found newlen before moving into next right subtree and passed len as oldlen .
        pathCount(root.left,len);
        sb.setLength(oldlen);
        pathCount(root.right,oldlen);
      return li;   
    }
    

  • 0

    Recursion is nicely done!!!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.