搜索二叉树是否是另一个二叉树的子树

时间:2014-10-16 18:06:25

标签: java recursion tree binary-tree

我遇到了一个严重的问题,即在第一个上重复搜索子树。

我试试这个但是......

public static boolean containsTree (Node t1, Node t2)
{
    if (t2 == null)
        return true;
    // Empty tree is always a subtree.
    else
        return subTree(t1, t2);
}

public static boolean subTree (Node t1, Node t2)
{
    if (t1 == null)
        return false; // Big tree is over.
    if (t1.getName().equalsIgnoreCase(t2.getName()))
        return matchTree(t1, t2);
    return (subTree(t1.getChild(), t2) || subTree(t1.getBrother(), t2));
}

private static boolean matchTree (Node t1, Node t2)
{
    if (t1 == null && t2 == null)
        return true; // Both trees are empty.
    if (t1 == null || t2 == null)
        return false; // Big tree empty and subtree still not found.
    if (!t1.getName().equalsIgnoreCase(t2.getName()))
        return false;
    return (matchTree(t1.getChild(), t2.getChild()) && matchTree(
            t1.getBrother(), t2.getBrother()));
}

似乎没有正确形成。 containsTree函数,当找到一个与onether one不同的节点时停止搜索。

下面,您可以找到两棵树的示例。

          1                 
         / \                                    3
        /   \                                   /\
       /     \                                 /  \
      2      3                                7    8
      /\     /\
     /  \   /  \
     3   4 5    6
                 \
                  3
                  /\
                 /  \
                 7   8

在这种情况下,当函数将右边的子树与左边的子树进行比较时,当find等于父节点但它具有不同的子节点时,它将停止搜索。 我需要该功能不要停止搜索,而是抛出这一点并搜索所有其他子节点及其子树。

1 个答案:

答案 0 :(得分:0)

说我们的班级是这样的:

class Node{
    node left, right;
    int value;    

    boolean equals(Node n){
        // if one child is null we can skip
        if(this.left == null && this.left != null ||
           this.left != null && this.left == null ){
            return false;
        }
        if(this.right == null && this.right != null ||
           this.right != null && this.right == null ){
            return false;
        }
        // 
        return (this.value == n.value) && 
               ( this.left == null || (this.left.equals(n.left)) ) && 
// if this.left == null, n.left is null too and the || will skip the equals()
               ( this.right == null || (this.right.equals(n.right)) );
// same for right
    }
}

此方法将递归检查树是否与另一棵树相同 所以,让我们检查它是否是一个子树:

boolean isSubTree(Node other){
    return this.equals(other) || 
         (other.left != null && this.isSubTree(other.left)) || 
// if left is null, this cant be a subtree 
         (other.right != null && this.isSubTree(other.right));
// same for right
}

没有测试,但我认为它可以像这样工作。我跳过了构造函数和其他函数。

(位重载返回语句:P)

你应该记住一些事情:树通常用于搜索值,并且大部分实现为二叉树:left-child< parent< right-child

修改

显然你应该确保你的树没有圈:P