这是我到目前为止的代码。我认为它非常接近。
public boolean sameStructure(OrderedSet<E> other) {
if (other.size() != size)
return false;
return sameStructureHelp(other, root, other.root);
}
private boolean sameStructureHelp(OrderedSet<E> other, TreeNode ref,
TreeNode otherRef) {
if (otherRef == null && ref != null)
return false;
if (otherRef != null && ref == null)
return false;
sameStructureHelp(other, ref.left, otherRef.left);
sameStructureHelp(other, ref.right, otherRef.right);
return true;
}
答案 0 :(得分:2)
你粘贴的东西大多是正确的,只是错过了一个关键部分:你应该返回它们的and
值,而不是仅仅检查左边和右边的子树,这意味着植根于当前节点的树是否满足条件是相同的结构。
答案 1 :(得分:0)
谢谢@Ziyao Wei 这是解决问题的代码:
public boolean sameStructure(OrderedSet<E> other) {
if (other.size() != size)
return false;
return sameStructureHelp(other, root, other.root);
}
private boolean sameStructureHelp(OrderedSet<E> other, TreeNode ref,
TreeNode otherRef) {
if (otherRef == null && ref != null)
return false;
if (otherRef != null && ref == null)
return false;
if (otherRef == null && ref == null)
return true;
return sameStructureHelp(other, ref.left, otherRef.left)
&& sameStructureHelp(other, ref.right, otherRef.right);
}