1. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

["1->2->5", "1->3"]
public class Solution {

    public List<String> binaryTreePaths(TreeNode root) {

        List<String> ans = new ArrayList<>();
        if(root == null) return ans;

        dfs(root, "", ans);
        return ans;
    }

    public void dfs(TreeNode root, String sub, List<String> ans) {


        if(root == null)
            return;

        if(root.left == null && root.right == null){
            ans.add(sub + root.val);
            return;
        }

        dfs(root.left, sub + root.val + "->", ans);
        dfs(root.right, sub + root.val + "->", ans);
    }
}

results matching ""

    No results matching ""