【二叉树】一棵树的子树是一颗树

xiaoxiao2021-02-28  81

题目链接:https://leetcode.com/problems/subtree-of-another-tree/#/description

/** * 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==NULL) return false; if(s->val==t->val){ return isSameTree(s,t)||isSubtree(s->left,t)||isSubtree(s->right,t); }else{ return isSubtree(s->left,t)||isSubtree(s->right,t); } } // 判断两棵树是不是相同 bool isSameTree(TreeNode* p, TreeNode* q) { if(p==NULL && q==NULL){ return true; }else if((p==NULL&&q!=NULL)||(p!=NULL&&q==NULL)||(q->val!=p->val)){ return false; }else{ bool tmp=isSameTree(p->left,q->left); bool tmp1=isSameTree(p->right,q->right); if(tmp&&tmp1) return true; else return false; } } };

转载请注明原文地址: https://www.6miu.com/read-84287.html

最新回复(0)