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.
給定兩棵非空二叉樹s和t,判定t是否為s的一棵子樹。

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.


思路
遞歸思想,本節(jié)點不滿足時則取兩個子節(jié)點判定結果的邏輯或,本節(jié)點滿足時則判定兩個子節(jié)點結果的邏輯與。

/**
 * 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 isSubtree(TreeNode* s, TreeNode* t) {
        if(s==nullptr) return false;
        if(isSame(s,t)) return true;
        return isSubtree(s->left,t) || isSubtree(s->right,t);
    }
    bool isSame(TreeNode* s, TreeNode* t){
        if(s==nullptr && t==nullptr) return true;
        if(s==nullptr || t==nullptr) return false;
        if(s->val != t->val) return false;
        return isSame(s->left,t->left) && isSame(s->right,t->right);
    }
};
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,899評論 0 33
  • 鄭號錫 今天他沒有去練習室,等一會吹很喜歡的你卻發(fā)現(xiàn)一些只是幻想,他還是在家里跳著女團舞蹈,你有些無奈,所...
    牽絆余生系列閱讀 184評論 0 0
  • 花開總有落,落花未落心。 人善終歸報,因果必輪回。 生無缺憾時,此處花又開。
    春城怡景閱讀 274評論 1 6
  • 每天下了班就跟個死人一樣了,身心俱疲。
    淡淡oo閱讀 165評論 0 0

友情鏈接更多精彩內(nèi)容