The problem is asking for an output of all paths in a binary tree in an arraylist of strings, with format a->b, if b is a child of a.
I am getting the following error messages, but I think I have "paths", "dfs" spelled and used correctly:
/code/Solution.java:41: error: cannot find symbol
paths.add(updated);
^
symbol: variable updated
location: class Solution
/code/Solution.java:46: error: cannot find symbol
dfs(paths, updated, toSearch.left);
^
symbol: variable updated
location: class Solution
/code/Solution.java:50: error: cannot find symbol
dfs(paths, updated, toSearch.right);
^
symbol: variable updated
location: class Solution
3 errors
Here is my code; I have commented my code for readability:
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the root of the binary tree
* @return: all root-to-leaf paths
*/
public List<String> binaryTreePaths(TreeNode root) {
// paths would be the arraylist holding all paths for returning
List<String> paths = new ArrayList<String>();
// dummy string to get the code started
String dummy = "";
// the first call to dfs
dfs(paths, dummy, root);
return paths;
}
/** This function adds to the arraylist "path" if the TreeNode toSearch is a leaf.
* Otherwise it recursively calls itself on the child nodes until reaching a leaf
**/
private void dfs(List<String> paths, String current, TreeNode toSearch){
// base case
if(toSearch == null){
return;
}
// this is to take care of the initial call when the String is empty - we do not want the string to start with "->".
if(current == ""){
String updated = Integer.toString(toSearch.val);
}else{
String updated = current + "->" + toSearch.val;
}
// if both children are null, then we can append the path to the list
if(toSearch.left == null && toSearch.right == null){
paths.add(updated);
return;
}
// if either node is not null, we keep searching.
if(toSearch.left != null){
dfs(paths, updated, toSearch.left);
}
if(toSearch.right != null){
dfs(paths, updated, toSearch.right);
}
}
}