You can easily do this with recursion. This following code works because two non-empty trees have the same shape if and only if their respective subtrees have the same shape.
boolean equalTrees(Node lhs, Node rhs) { // Empty trees are equal if (lhs == null && rhs == null) return true; // Empty tree is not equal to a non-empty one if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) return false; // otherwise check recursively return equalTrees(lhs.left(), rhs.left()) && equalTrees(lhs.right(), rhs.right()) }
To test two trees, translate their root nodes into the above function.
equalTrees(tree1.root(), tree2.root())
source share