Easy to understand, recursive solutions with StringBuilder


  • 1
    A

    Idea is to before adding new characters to the StringBuilder, store the length of it, and when done with recursion, set the length back to the initial value. We need to store the length because we don't know how many digits a node's value have.

    public class Solution {   
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> paths = new ArrayList<>();
            
            path(root, new StringBuilder(), paths);
    
            return paths;
        }
        
        private void path(TreeNode root, StringBuilder sb, List<String> list) {
            if (root == null) return;
            
            if (root.left == null && root.right == null) {
                int len = sb.length();
                sb.append(root.val);
                list.add(sb.toString());
                sb.setLength(len); 
                return;
            }
            
            if (root.left != null) {
                int len = sb.length();
                sb.append(root.val + "->");
                path(root.left, sb, list);
                sb.setLength(len);
            }
            
            if (root.right != null) {
                int len = sb.length();
                sb.append(root.val + "->");
                path(root.right, sb, list);
                sb.setLength(len);
            }
        }
    }

Log in to reply
 

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