• 572. Subtree of Another Tree


    Problem statement:

    Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree scould also be considered as a subtree of itself.

    Example 1:
    Given tree s:

         3
        / 
       4   5
      / 
     1   2
    

    Given tree t:

       4 
      / 
     1   2
    

    Return true, because t has the same structure and node values with a subtree of s.

    Example 2:
    Given tree s:

         3
        / 
       4   5
      / 
     1   2
        /
       0
    

    Given tree t:

       4
      / 
     1   2
    

    Return false.

    Solution:

    Two extra functions to solve this problem
    void find_node() : find all nodes whose value are equal to the root of t.
    bool is_subtree(): find if any start node can for a subtree which is same with t.

    class Solution {
    public:
        bool isSubtree(TreeNode* s, TreeNode* t) {
            vector<TreeNode*> node_set;
            find_node(s, t, node_set);
            for(auto node : node_set){
                if(is_subtree(node, t)){
                    return true;
                }
            }
            return false;
        }
        
    private:
        void find_node(TreeNode* s, TreeNode* t, vector<TreeNode*>& node_set){
            if(s == NULL){
                return;
            }
            if(s->val == t->val){
                node_set.push_back(s);
            }
            find_node(s->left, t, node_set);
            find_node(s->right, t, node_set);
            return;
        }
    bool is_subtree(TreeNode* s, TreeNode* t){
            if(s == NULL && t == NULL){
                return true;    
            }
            if((s != NULL && t == NULL) || (s == NULL && t != NULL) || (s->val != t->val)){
                return false;
            }
            return is_subtree(s->left, t->left) && is_subtree(s->right, t->right);
        }
    };
  • 相关阅读:
    JDBC05JDBC控制事务4
    JDBC05详解各个类2
    JDBC05JDBC工具类3
    Tomcat&Servlet7_Tomcat2
    MySQL多表&事务04事务2
    JDBC连接池&JDBCTemplate06_Spring JDBC2
    JDBC连接池&JDBCTemplate06_数据库连接池1
    Tomcat&Servlet7_web服务器软件概述1
    MySQL多表&事务04DCL3
    用 JavaScript 的匿名函数理解 C# 的委托
  • 原文地址:https://www.cnblogs.com/wdw828/p/6823690.html
Copyright © 2020-2023  润新知