欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[LeetCode] Subtree of Another Tree

程序员文章站 2022-07-15 12:30:20
...

题目链接:点击打开链接

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树递归比较。整理了一下递归函数就可以运行了。试探性地交一发,居然没有TLE,还超过了78.67%的提交......

[LeetCode] Subtree of Another Tree

果然不能把LeetCode当成ACM来打= =

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool cmp(TreeNode* s, TreeNode* t)
    {
        if(s==NULL&&t==NULL)return true;
        if(s==NULL||t==NULL)return false;
        if(s->val==t->val)
        {
            return cmp(s->left,t->left)&&cmp(s->right,t->right);
        }
        else return false;
    }
    bool isSubtree(TreeNode* s, TreeNode* t) {
        if(s==NULL&&t==NULL)return true;
        if(s==NULL||t==NULL)return false;
        if(cmp(s,t))return true;
        else return isSubtree(s->left,t)||isSubtree(s->right,t);
    }
};