[LeetCode] 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樹遞歸比較。整理了一下遞歸函數就可以運行了。試探性地交一發,居然沒有TLE,還超過了78.67%的提交......


果然不能把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);
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章