📌  相关文章
📜  检查一棵二叉树是否是另一棵二叉树的子树 |设置 1

📅  最后修改于: 2022-05-13 01:57:19.836000             🧑  作者: Mango

检查一棵二叉树是否是另一棵二叉树的子树 |设置 1

给定两棵二叉树,检查第一棵树是否是第二棵树的子树。树 T 的子树是由 T 中的一个节点及其在 T 中的所有后代组成的树 S。根节点对应的子树就是整棵树;对应于任何其他节点的子树称为适当子树。
例如,在以下情况下,树 S 是树 T 的子树。

Tree 2
          10  
        /    \ 
      4       6
       \
        30

Tree 1
              26
            /   \
          10     3
        /    \     \
      4       6      3
       \
        30

解决方案:以前序方式遍历树 T。对于遍历中的每个访问节点,查看以该节点为根的子树是否与 S 相同。
以下是对此的实现。

C++
// C++ program to check if binary tree
// is subtree of another binary tree
#include
using namespace std;
 
/* A binary tree node has data,
left child and right child */
class node
{
    public:
    int data;
    node* left;
    node* right;
};
 
/* A utility function to check
whether trees with roots as root1 and
root2 are identical or not */
bool areIdentical(node * root1, node *root2)
{
    /* base cases */
    if (root1 == NULL && root2 == NULL)
        return true;
 
    if (root1 == NULL || root2 == NULL)
        return false;
 
    /* Check if the data of both roots is
    same and data of left and right
    subtrees are also same */
    return (root1->data == root2->data &&
            areIdentical(root1->left, root2->left) &&
            areIdentical(root1->right, root2->right) );
}
 
 
/* This function returns true if S
is a subtree of T, otherwise false */
bool isSubtree(node *T, node *S)
{
    /* base cases */
    if (S == NULL)
        return true;
 
    if (T == NULL)
        return false;
 
    /* Check the tree with root as current node */
    if (areIdentical(T, S))
        return true;
 
    /* If the tree with root as current
    node doesn't match then try left
    and right subtrees one by one */
    return isSubtree(T->left, S) ||
        isSubtree(T->right, S);
}
 
 
/* Helper function that allocates
a new node with the given data
and NULL left and right pointers. */
node* newNode(int data)
{
    node* Node = new node();
    Node->data = data;
    Node->left = NULL;
    Node->right = NULL;
    return(Node);
}
 
/* Driver code*/
int main()
{
    // TREE 1
    /* Construct the following tree
            26
            / \
        10 3
        / \ \
    4 6 3
    \
        30
    */
    node *T = newNode(26);
    T->right         = newNode(3);
    T->right->right = newNode(3);
    T->left         = newNode(10);
    T->left->left     = newNode(4);
    T->left->left->right = newNode(30);
    T->left->right     = newNode(6);
 
    // TREE 2
    /* Construct the following tree
        10
        / \
    4 6
    \
        30
    */
    node *S = newNode(10);
    S->right     = newNode(6);
    S->left     = newNode(4);
    S->left->right = newNode(30);
 
 
    if (isSubtree(T, S))
        cout << "Tree 2 is subtree of Tree 1";
    else
        cout << "Tree 2 is not a subtree of Tree 1";
 
    return 0;
}
 
// This code is contributed by rathbhupendra


C
#include 
#include 
 
/* A binary tree node has data, left child and right child */
struct node
{
    int data;
    struct node* left;
    struct node* right;
};
 
/* A utility function to check whether trees with roots as root1 and
   root2 are identical or not */
bool areIdentical(struct node * root1, struct node *root2)
{
    /* base cases */
    if (root1 == NULL && root2 == NULL)
        return true;
 
    if (root1 == NULL || root2 == NULL)
        return false;
 
    /* Check if the data of both roots is same and data of left and right
       subtrees are also same */
    return (root1->data == root2->data   &&
            areIdentical(root1->left, root2->left) &&
            areIdentical(root1->right, root2->right) );
}
 
 
/* This function returns true if S is a subtree of T, otherwise false */
bool isSubtree(struct node *T, struct node *S)
{
    /* base cases */
    if (S == NULL)
        return true;
 
    if (T == NULL)
        return false;
 
    /* Check the tree with root as current node */
    if (areIdentical(T, S))
        return true;
 
    /* If the tree with root as current node doesn't match then
       try left and right subtrees one by one */
    return isSubtree(T->left, S) ||
           isSubtree(T->right, S);
}
 
 
/* Helper function that allocates a new node with the given data
   and NULL left and right pointers. */
struct node* newNode(int data)
{
    struct node* node =
        (struct node*)malloc(sizeof(struct node));
    node->data  = data;
    node->left  = NULL;
    node->right = NULL;
    return(node);
}
 
/* Driver program to test above function */
int main()
{
    // TREE 1
    /* Construct the following tree
              26
            /   \
          10     3
        /    \     \
      4      6      3
       \
        30
    */
    struct node *T        = newNode(26);
    T->right              = newNode(3);
    T->right->right       = newNode(3);
    T->left               = newNode(10);
    T->left->left         = newNode(4);
    T->left->left->right  = newNode(30);
    T->left->right        = newNode(6);
 
    // TREE 2
    /* Construct the following tree
          10
        /    \
      4      6
       \
        30
    */
    struct node *S    = newNode(10);
    S->right          = newNode(6);
    S->left           = newNode(4);
    S->left->right    = newNode(30);
 
 
    if (isSubtree(T, S))
        printf("Tree 2 is subtree of Tree 1");
    else
        printf("Tree 2 is not a subtree of Tree 1");
 
    getchar();
    return 0;
}


Java
// Java program to check if binary tree is subtree of another binary tree
  
// A binary tree node
class Node
{
    int data;
    Node left, right, nextRight;
  
    Node(int item)
    {
        data = item;
        left = right = nextRight = null;
    }
}
  
class BinaryTree
{
    Node root1,root2;
  
    /* A utility function to check whether trees with roots as root1 and
       root2 are identical or not */
    boolean areIdentical(Node root1, Node root2)
    {
  
        /* base cases */
        if (root1 == null && root2 == null)
            return true;
  
        if (root1 == null || root2 == null)
            return false;
  
        /* Check if the data of both roots is same and data of left and right
           subtrees are also same */
        return (root1.data == root2.data
                && areIdentical(root1.left, root2.left)
                && areIdentical(root1.right, root2.right));
    }
  
    /* This function returns true if S is a subtree of T, otherwise false */
    boolean isSubtree(Node T, Node S)
    {
        /* base cases */
        if (S == null)
            return true;
  
        if (T == null)
            return false;
  
        /* Check the tree with root as current node */
        if (areIdentical(T, S))
            return true;
  
        /* If the tree with root as current node doesn't match then
           try left and right subtrees one by one */
        return isSubtree(T.left, S)
                || isSubtree(T.right, S);
    }
  
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
          
        // TREE 1
        /* Construct the following tree
              26
             /   \
            10     3
           /    \     \
          4      6      3
           \
            30  */
           
        tree.root1 = new Node(26);
        tree.root1.right = new Node(3);
        tree.root1.right.right = new Node(3);
        tree.root1.left = new Node(10);
        tree.root1.left.left = new Node(4);
        tree.root1.left.left.right = new Node(30);
        tree.root1.left.right = new Node(6);
  
        // TREE 2
        /* Construct the following tree
           10
         /    \
         4      6
          \
          30  */
           
        tree.root2 = new Node(10);
        tree.root2.right = new Node(6);
        tree.root2.left = new Node(4);
        tree.root2.left.right = new Node(30);
  
        if (tree.isSubtree(tree.root1, tree.root2))
            System.out.println("Tree 2 is subtree of Tree 1 ");
        else
            System.out.println("Tree 2 is not a subtree of Tree 1");
    }
}
  
// This code has been contributed by Mayank Jaiswal


Python3
# Python program to check binary tree is a subtree of
# another tree
 
# A binary tree node
class Node:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# A utility function to check whether trees with roots
# as root 1 and root2 are indetical or not
def areIdentical(root1, root2):
     
    # Base Case
    if root1 is None and root2 is None:
        return True
    if root1 is None or root2 is None:
        return False
 
    # Check fi the data of both roots is same and data of
    # left and right subtrees are also same
    return (root1.data == root2.data and
            areIdentical(root1.left , root2.left)and
            areIdentical(root1.right, root2.right)
            )
 
# This function returns True if S is a subtree of T,
# otherwise False
def isSubtree(T, S):
     
    # Base Case
    if S is None:
        return True
 
    if T is None:
        return False
 
    # Check the tree with root as current node
    if (areIdentical(T, S)):
        return True
 
    # IF the tree with root as current node doesn't match
    # then try left and right subtreee one by one
    return isSubtree(T.left, S) or isSubtree(T.right, S)
 
 
# Driver program to test above function
 
""" TREE 1
     Construct the following tree
              26
            /   \
          10     3
        /    \     \
      4      6      3
       \
        30
    """
 
T = Node(26)
T.right = Node(3)
T.right.right  = Node(3)
T.left = Node(10)
T.left.left = Node(4)
T.left.left.right = Node(30)
T.left.right = Node(6)
 
""" TREE 2
     Construct the following tree
          10
        /    \
      4      6
       \
        30
    """
S = Node(10)
S.right = Node(6)
S.left = Node(4)
S.left.right = Node(30)
 
if isSubtree(T, S):
    print ("Tree 2 is subtree of Tree 1")
else :
    print ("Tree 2 is not a subtree of Tree 1")
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#
// C# program to check if binary tree
// is subtree of another binary tree
using System;
 
// A binary tree node
class Node
{
    public int data;
    public Node left, right, nextRight;
 
    public Node(int item)
    {
        data = item;
        left = right = nextRight = null;
    }
}
 
public class BinaryTree
{
    Node root1,root2;
 
    /* A utility function to check whether
        trees with roots as root1 and
        root2 are identical or not */
    bool areIdentical(Node root1, Node root2)
    {
 
        /* base cases */
        if (root1 == null && root2 == null)
            return true;
 
        if (root1 == null || root2 == null)
            return false;
 
        /* Check if the data of both roots is
        same and data of left and right
        subtrees are also same */
        return (root1.data == root2.data
                && areIdentical(root1.left, root2.left)
                && areIdentical(root1.right, root2.right));
    }
 
    /* This function returns true if S is
    a subtree of T, otherwise false */
    bool isSubtree(Node T, Node S)
    {
        /* base cases */
        if (S == null)
            return true;
 
        if (T == null)
            return false;
 
        /* Check the tree with root as current node */
        if (areIdentical(T, S))
            return true;
 
        /* If the tree with root as current
          node doesn't match then try left
          and right subtrees one by one */
        return isSubtree(T.left, S)
                || isSubtree(T.right, S);
    }
 
    // Driver code
    public static void Main()
    {
        BinaryTree tree = new BinaryTree();
         
        // TREE 1
        /* Construct the following tree
            26
            / \
            10 3
        / \ \
        4 6 3
        \
            30 */
             
        tree.root1 = new Node(26);
        tree.root1.right = new Node(3);
        tree.root1.right.right = new Node(3);
        tree.root1.left = new Node(10);
        tree.root1.left.left = new Node(4);
        tree.root1.left.left.right = new Node(30);
        tree.root1.left.right = new Node(6);
 
        // TREE 2
        /* Construct the following tree
        10
        / \
        4 6
        \
        30 */
             
        tree.root2 = new Node(10);
        tree.root2.right = new Node(6);
        tree.root2.left = new Node(4);
        tree.root2.left.right = new Node(30);
 
        if (tree.isSubtree(tree.root1, tree.root2))
            Console.WriteLine("Tree 2 is subtree of Tree 1 ");
        else
            Console.WriteLine("Tree 2 is not a subtree of Tree 1");
    }
}
 
/* This code is contributed by Rajput-Ji*/


Javascript


输出:

Tree 2 is subtree of Tree 1 

时间复杂度:上述解决方案的时间最坏情况复杂度为 O(mn),其中 m 和 n 是给定两棵树中的节点数。

辅助空间: O(n)

我们可以在 O(n) 时间内解决上述问题。请参考 检查一棵二叉树是否是另一棵二叉树的子树 |为 O(n) 解决方案设置 2。