Java 比较两个二叉树,看它们是否具有相同的结构

Java 比较两个二叉树,看它们是否具有相同的结构,java,data-structures,binary-tree,binary-search-tree,Java,Data Structures,Binary Tree,Binary Search Tree,另一个简单的,但我似乎无法得到它。我需要编写一个方法来比较两个二叉树的结构,并返回它们是否相同。数据和数据类型不仅对结构很重要。以下是一些例子: 这是我到目前为止的代码。我认为这真的很接近 public boolean sameStructure(OrderedSet<E> other) { if (other.size() != size) return false; return sameStructureHelp(other, root, ot

另一个简单的,但我似乎无法得到它。我需要编写一个方法来比较两个二叉树的结构,并返回它们是否相同。数据和数据类型不仅对结构很重要。以下是一些例子:

这是我到目前为止的代码。我认为这真的很接近

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;

}
公共布尔sameStructure(OrderedSet-other){
如果(其他.size()!=大小)
返回false;
返回sameStructureHelp(other,root,other.root);
}
私有布尔sameStructureHelp(OrderedSet-other,TreeNode-ref,
TreeNode(其他参考){
if(otherRef==null&&ref!=null)
返回false;
if(otherRef!=null&&ref==null)
返回false;
sameStructureHelp(其他,参考左侧,其他参考左侧);
同一结构帮助(其他,参考权利,其他参考权利);
返回true;
}

您粘贴的内容大部分是正确的,只是缺少了一个关键部分:您应该返回它们的
值,这意味着当前节点中的树是否满足相同结构的条件。

谢谢@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);

}
公共布尔sameStructure(OrderedSet-other){
如果(其他.size()!=大小)
返回false;
返回sameStructureHelp(other,root,other.root);
}
私有布尔sameStructureHelp(OrderedSet-other,TreeNode-ref,
TreeNode(其他参考){
if(otherRef==null&&ref!=null)
返回false;
if(otherRef!=null&&ref==null)
返回false;
if(otherRef==null&&ref==null)
返回true;
返回相同的结构帮助(其他,参考左侧,参考左侧)
&&同一结构帮助(其他,参考权利,其他参考权利);
}

您的主张是什么?仔细看一下,如果两个节点同时为null,代码会抛出NullPointerException,不是吗?