class Solution {
private void preorderTraversal(TreeNode root, List<Integer> answer) {
if (root == null) {
return;
}
answer.add(root.val);
preorderTraversal(root.left, answer);
preorderTraversal(root.right, answer);
}
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> answer = new ArrayList<>();
preorderTraversal(root, answer);
return answer;
}
}
Why do i need a helper function?
I tried implementing the traversal using only one function.I expected this to work without any additional helper function.
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> answer = new ArrayList<>();
if (root == null) {
return;
}
answer.add(root.val);
preorderTraversal(root.left, answer);
preorderTraversal(root.right, answer);
return answer;
}
Your attempt calls the function recursively with 2 arguments, but there is no function with that signature.
Note also that your base case
returnis not valid, as your function is supposed to return an ArrayList, so doreturn answer;.It is however possible to do it without helper function. You should then capture the returned ArrayList from the recursive calls, and add those contents to your current ArrayList:
But this is not so memory efficient as the version with the helper function, which only needs one ArrayList and no values need to be copied from one ArrayList to another.