Share my solution which beats 96.4% JAVA


  • 0
    A
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            // base case
            if (root == null) return new ArrayList<String>();
            
            List<String> res = new ArrayList<String>();
            StringBuilder sb = new StringBuilder();
            binaryTreePaths(root, sb, res);
            return res;
            
        }
        
        private void binaryTreePaths(TreeNode root, StringBuilder sb, List<String> list) {
            // base caes
            if (root == null) return;
            
            int len = sb.length();
            
            if (sb.length() == 0) {
                sb.append(root.val);
            }
            else {
                sb.append("->").append(root.val);
            }
            
            if (root.left == null && root.right == null) {
                list.add(sb.toString());
                sb.setLength(len);
                return;
            }
            
            
            
            
            binaryTreePaths(root.left, sb, list);
            binaryTreePaths(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.