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é)點(diǎn)不滿足時(shí)則取兩個(gè)子節(jié)點(diǎn)判定結(jié)果的邏輯或,本節(jié)點(diǎn)滿足時(shí)則判定兩個(gè)子節(jié)點(diǎn)結(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);
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

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