zoukankan      html  css  js  c++  java
  • 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);
        }
    };
  • 相关阅读:
    [From 3.1~3.4]
    [From 2.7]简单应用程序部署(程序集打包)
    [From 2.4]C#编译器和程序集链接器(以及一些它们的命令开关)
    [From 2.3]托管PE文件的组成
    [From 1.1~1.2]CLR的执行模型
    项目开发日志:Build AssetBundle——SpriteAtlas(已解惑)
    JDK所有版本下载链接
    Maven
    SEO优化
    Mysql字符集
  • 原文地址:https://www.cnblogs.com/wdw828/p/6823690.html
Copyright © 2011-2022 走看看