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 };
  • 相关阅读:
    ext表格范例
    基于对象的EXT组件间通信
    hibernate自定义生成主健
    Amcharts
    ExtJS之面向对象编程基本知识
    在Ext里写大应用 (翻译:米米饭)
    EXT表单常用验证
    JPA 复合主键
    PowerDesign15常用技巧
    spring security和EXT
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8581133.html
Copyright © 2011-2022 走看看