I am trying to solve this problem https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ , i.e. preorder traversal with recursive slution.
EDIT: The whole code:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
static List<Integer> res = new ArrayList<Integer>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null){
return new ArrayList<Integer>();
}
res.add(root.val);
if(root.left != null){
res.add(preorderTraversal(root.left));
}
if(root.right != null){
res.add(preorderTraversal(root.right));
}
return res;
}
}
I have wrong answer because of the following:
Input: {1,2}
Output: [1,1,2]
Expected: [1,2]
Can someone tell me how to fix this?
EDIT: I dont have main()
method or unit tests. If you open the link that I posted you will see that this is online judging system.