Java solution with StringBuilder and Backtracking


  • 0
    A
    public class Solution {
        
        public int countDigits(int num) {
            int ret = 0;
            while(num != 0) {
                num /= 10;
                ret++;
            }
            
            return ret;
        }
        
        public void getPaths(List<String> ret, StringBuilder sb, TreeNode node) {
            sb.append(node.val);
            int digits = countDigits(node.val);
            if(node.val < 0) digits++;
            
            if(node.left == null && node.right == null) {
                ret.add(sb.toString());
                sb.delete(sb.length()-digits, sb.length());
                return;
            }
            
            sb.append("->");
            if(node.left != null) getPaths(ret, sb, node.left);
            if(node.right != null) getPaths(ret, sb, node.right);
            sb.delete(sb.length()-digits-2, sb.length());
        }
        
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> ret = new ArrayList<>();
            if(root == null) return ret;
            getPaths(ret, new StringBuilder(), root);
            
            return ret;
        }
    }

Log in to reply
 

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