LeetCode – Binary Tree Paths (Java)

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

Java Solution

A typical depth-first search problem.

public List<String> binaryTreePaths(TreeNode root) {
    ArrayList<String> finalResult = new ArrayList<String>();
 
    if(root==null)
        return finalResult;
 
    ArrayList<String> curr = new ArrayList<String>();
    ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
 
    dfs(root, results, curr);
 
    for(ArrayList<String> al : results){
        StringBuilder sb = new StringBuilder();
        sb.append(al.get(0));
        for(int i=1; i<al.size();i++){
            sb.append("->"+al.get(i));
        }
 
        finalResult.add(sb.toString());
    }
 
    return finalResult;
}
 
public void dfs(TreeNode root, ArrayList<ArrayList<String>> list, ArrayList<String> curr){
    curr.add(String.valueOf(root.val));
 
    if(root.left==null && root.right==null){
        list.add(curr);
        return;
    }
 
    if(root.left!=null){
        ArrayList<String> temp = new ArrayList<String>(curr);
        dfs(root.left, list, temp);
    }
 
    if(root.right!=null){
        ArrayList<String> temp = new ArrayList<String>(curr);
        dfs(root.right, list, temp);
    } 
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Rush


    public class Solution
    {
    List result = new ArrayList();
    StringBuilder sb = new StringBuilder();

    public List binaryTreePaths(TreeNode root)
    {
    if(root == null)
    return result;

    int cntr = sb.length();
    if(root.left == null && root.right == null)
    {
    sb.append(root.val);
    result.add(sb.toString());
    sb.delete(cntr,sb.length());
    }
    if(root.left != null)
    {
    sb.append(root.val);
    sb.append("->");
    binaryTreePaths(root.left);
    sb.delete(cntr,sb.length());
    }
    if(root.right != null)
    {
    sb.append(root.val);
    sb.append("->");
    binaryTreePaths(root.right);
    sb.delete(cntr,sb.length());
    }
    return result;
    }
    }