DFS Java Solution (AC) w/ StringBuilder


  • 1
    V
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> result = new ArrayList<String>();
            dfs(root, new StringBuilder(), result);
            return result;
        }
        
        public void dfs(TreeNode root, StringBuilder sb, List<String> result) {
            if(root == null) {
                return;
            }
            
            int length = sb.length();
            if(root.left == null && root.right == null) {
                sb.append(root.val);
                result.add(sb.toString());
                sb.setLength(length);
                return;
            }
            
            sb.append(String.valueOf(root.val)).append("->");
            dfs(root.left, sb, result);
            dfs(root.right, sb, result);
            sb.setLength(length);
        }
    }
    

Log in to reply
 

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