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

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

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

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

例子:

朴素方法:朴素方法在该问题的Set-1中进行了讨论。

高效方法:基于从树的中序和前序/后序遍历中唯一识别树的有效方法在本问题的Set-2中进行了讨论。

Alternative Efficient Approach:该方法是在Tree-T中找到与Tree-S高度相同的所有节点,然后进行比较。

  • 最初计算给定子树的高度( Tree -S )。
  • 在下一步中,从Tree-T中找到所有高度为Tree-S高度的节点, 并存储他们的地址。
  • 然后从每个节点,我们存储我们检查它是否是一个相同的子树。
  • 在这种方法中,不需要检查所有节点是否是相同的子树,因为我们将高度作为必须执行实际相同子树验证的参数。

下面是上面的实现。

C++
// C++ program to check if a binary tree
// Is subtree of another binary tree
 
#include 
using namespace std;
 
// Structure of a Binary Tree Node
struct Node {
    int data;
    struct Node *left, *right;
};
 
// Utility function to
// Create a new tree node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Function to calculate
// The height of the tree
int height_of_tree(Node* root)
{
    if (!root)
        return 0;
 
    // Calculate the left subtree
    // And right subtree height
    int left = height_of_tree(root->left);
    int right = height_of_tree(root->right);
    return 1 + max(left, right);
}
 
// Function to check
// It is a subtree or not
bool CheckSubTree(Node* T, Node* S)
{
    if (S == NULL && T == NULL)
        return true;
 
    if (T == NULL || S == NULL)
        return false;
 
    if (T->data != S->data)
        return false;
 
    return CheckSubTree(T->left, S->left)
           && CheckSubTree(T->right, S->right);
}
 
// Function to extract the
// nodes of height of the subtree
// i.e tree-S from the parent
// tree(T-tree) using the height of the tree
int subtree_height(Node* root,
                   vector& nodes,
                   int h)
{
    if (root == NULL)
        return 0;
 
    else {
 
        // Calculating the height
        // Of the tree at each node
        int left = subtree_height(root->left,
                                  nodes, h);
 
        int right = subtree_height(root->right,
                                   nodes, h);
 
        int height = max(left, right) + 1;
 
        // If height equals to height
        // of the subtree then store it
        if (height == h)
            nodes.push_back(root);
 
        return height;
    }
}
 
// Function to check if it is a subtree
bool isSubTree(Node* T, Node* S)
{
    if (T == NULL && S == NULL)
        return true;
 
    if (T == NULL || S == NULL)
        return false;
 
    // Calling the height_of_tree
    // Function to calculate
    // The height of subtree-S
    int h = height_of_tree(S);
    vector nodes;
 
    // Calling the subtree_height
    // To extract all the nodes
    // Of height of subtree(S) i.e height-h
    int h1 = subtree_height(T, nodes, h);
 
    bool result = false;
    int n = nodes.size();
 
    for (int i = 0; i < n; i++) {
 
        // If the data of the
        // node of tree-T at height-h
        // is equal to the data
        // of root of subtree-S
        // then check if is a subtree
        // of the parent tree or not
        if (nodes[i]->data == S->data)
            result = CheckSubTree(nodes[i], S);
 
        // If any node is satisfying
        // the CheckSubTree then return true
        if (result)
            return true;
    }
    // If no node is satisfying
    // the subtree the return false
    return false;
}
 
// Driver program
int main()
{
    // Create binary tree T in above diagram
    Node* T = newNode(1);
    T->left = newNode(2);
    T->right = newNode(3);
    T->left->left = newNode(4);
    T->left->right = newNode(5);
    T->right->left = newNode(6);
 
    // Create binary tree S shown in diagram
    Node* S = newNode(3);
    S->left = newNode(6);
 
    // Lets us call the function
    // isSubTree() which checks
    // that the given Tree -S is a subtree
    // of tree -T(parent tree)
    if (isSubTree(T, S))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}


Python3
# Python program to check if a binary tree
# Is subtree of another binary tree
 
# Structure of a Binary Tree Node
from platform import node
 
class Node:
    def __init__(self,data):
        self.data = data
        self.left = self.right = None
     
# Utility function to
# Create a new tree node
def newNode(data):
 
    temp = Node(data)
    return temp
 
# Function to calculate
# The height of the tree
def height_of_tree(root):
 
    if (root == None):
        return 0
 
    # Calculate the left subtree
    # And right subtree height
    left = height_of_tree(root.left)
    right = height_of_tree(root.right)
    return 1 + max(left, right)
 
 
# Function to check
# It is a subtree or not
def CheckSubTree(T, S):
 
    if (S == None and T == None):
        return True
 
    if (T == None or S == None):
        return False
 
    if (T.data != S.data):
        return False
 
    return CheckSubTree(T.left, S.left) and CheckSubTree(T.right, S.right)
 
# Function to extract the
# nodes of height of the subtree
# i.e tree-S from the parent
# tree(T-tree) using the height of the tree
def subtree_height(root,nodes,h):
 
    if (root == None):
        return 0
 
    else:
 
        # Calculating the height
        # Of the tree at each node
        left = subtree_height(root.left,nodes, h)
 
        right = subtree_height(root.right, nodes, h)
 
        height = max(left, right) + 1
 
        # If height equals to height
        # of the subtree then store it
        if (height == h):
            nodes.append(root)
 
        return height
 
# Function to check if it is a subtree
def isSubTree(T, S):
 
    if (T == None and S == None):
        return True
 
    if (T == None or S == None):
        return False
 
    # Calling the height_of_tree
    # Function to calculate
    # The height of subtree-S
    h = height_of_tree(S)
    nodes = []
 
    # Calling the subtree_height
    # To extract all the nodes
    # Of height of subtree(S) i.e height-h
    h1 = subtree_height(T, nodes, h)
 
    result = False
    n = len(nodes)
 
    for i in range(n):
 
        # If the data of the
        # node of tree-T at height-h
        # is equal to the data
        # of root of subtree-S
        # then check if is a subtree
        # of the parent tree or not
        if (nodes[i].data == S.data):
            result = CheckSubTree(nodes[i], S)
 
        # If any node is satisfying
        # the CheckSubTree then return true
        if (result):
            return True
    # If no node is satisfying
    # the subtree the return false
    return False
 
# Driver program
 
# Create binary tree T in above diagram
T = newNode(1)
T.left = newNode(2)
T.right = newNode(3)
T.left.left = newNode(4)
T.left.right = newNode(5)
T.right.left = newNode(6)
 
# Create binary tree S shown in diagram
S = newNode(3)
S.left = newNode(6)
 
# Lets us call the function
# isSubTree() which checks
# that the given Tree -S is a subtree
# of tree -T(parent tree)
if (isSubTree(T, S)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by shinjanpatra


Javascript



输出
Yes

时间复杂度: O(N)
辅助空间: O( 2 H ) 其中 H 是 Tree-T 的高度