Elegant & Simple JAVA solution. No need of helper function.


  • 0
    R
    public class Solution 
    {
        List<String> result = new ArrayList<String>();
        StringBuilder sb = new StringBuilder();
        
        public List<String> binaryTreePaths(TreeNode root) 
        {
            if(root == null)
                return result;
            
            int cntr = sb.length();
            if(root.left == null && root.right == null)
            {
                sb.append(root.val);
                result.add(sb.toString());
                sb.delete(cntr,sb.length());
            }    
            if(root.left != null)
            {
                sb.append(root.val);
                sb.append("->");
                binaryTreePaths(root.left);
                sb.delete(cntr,sb.length());
            }
            if(root.right != null)
            {
                sb.append(root.val);
                sb.append("->");
                binaryTreePaths(root.right);
                sb.delete(cntr,sb.length());            
            }
    
            return result;
        }
    }
    

Log in to reply
 

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