I'm trying to check symmetry in a given tree, my idea was that i could make two Arraylists from the left subtree with pre order traversal(NLR) and from the right subtree with reverse preorder traversal(NRL), and then compare the two with equality operator and I would have a boolean value. I've checked the returning Arraylist values but it seems to always seem to give back false no matter any of the matching value in Arraylists. Any tips on why this is happening is appreciated.
import java.util.ArrayList;
class BinaryTree<E>{
public E data;
public BinaryTree<E> left;
public BinaryTree<E> right;
public BinaryTree() {}
public BinaryTree(E data) { this.data = data; }
public BinaryTree(E data, BinaryTree<E> left, BinaryTree<E> right) {
this.data = data;
this.left = left;
this.right = right;
}
}
class Solution{
public static boolean symmetricTree(BinaryTree<Integer> root){
System.out.println(traversal(root.left, true));
System.out.println(traversal(root.right, false));
return traversal(root.left, true) == traversal(root.right, false);
}
public static ArrayList<Integer> traversal(BinaryTree<Integer> root, boolean left){
// 関数を完成させてください
ArrayList<Integer> dArr = new ArrayList<>();
if(left) dArr = preorderTraversalHelper(root, dArr);
else dArr = reversePreorderTraversalHelper(root, dArr);
//System.out.println(dArr);
return dArr;
}
public static ArrayList<Integer> preorderTraversalHelper(BinaryTree<Integer> root, ArrayList<Integer> dArr){
if (root == null) return null;
dArr.add(root.data);
preorderTraversalHelper(root.left, dArr);
preorderTraversalHelper(root.right, dArr);
return dArr;
}
public static ArrayList<Integer> reversePreorderTraversalHelper(BinaryTree<Integer> root, ArrayList<Integer> dArr){
if (root == null) return null;
dArr.add(root.data);
reversePreorderTraversalHelper(root.right, dArr);
reversePreorderTraversalHelper(root.left, dArr);
return dArr;
}
}