• 572. Subtree of Another Tree


    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 s could 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.

    判断树s是否包含树t

    C++(29ms):

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool isSubtree(TreeNode* s, TreeNode* t) {
    13         if (s == NULL)
    14             return false ;
    15         if (isSame(s,t))
    16             return true ;
    17         return isSubtree(s->left , t) || isSubtree(s->right , t) ;
    18     }
    19     
    20     bool isSame(TreeNode* s, TreeNode* t){
    21         if (s == NULL && t == NULL)
    22             return true ;
    23         if (s == NULL || t == NULL)
    24             return false ;
    25         if (s->val != t->val)
    26             return false ;
    27         return isSame(s->left , t->left) && isSame(s->right , t->right) ;
    28     }
    29 };
  • 相关阅读:
    docker部署数据库
    JAVA 删除Map中元素(JDK8)
    Docker 学习记录基于Linux
    Liunx 操作命令学习记录
    NACOS 认识和学习
    SpringCloud 学习及其相关组件的认识
    springBoot 配置文件的优先级
    配置redisTemplate的序列化
    springBoot 使用测试类报错
    注解反射的认识
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8581133.html
Copyright © 2020-2023  润新知