zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    错误:找不到或无法加载主类
    CentOS 7 命令
    CentOS 7 分区
    Pow(x, n)
    Sum Root to Leaf Numbers
    linux下intel 82579LM 网卡驱动安装
    printf打印字符耗时多少
    数组中移动0至后面
    SDL多线程问题之--Unknown request in queue while dequeuing
    java学习123>>IO
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8581133.html
Copyright © 2011-2022 走看看