其他分享
首页 > 其他分享> > LeetCode572. 另一个树的子树

LeetCode572. 另一个树的子树

作者:互联网

题目

本题目一开始想要通过二叉树遍历KMP匹配,但看来实现比较复杂

不如直接暴力匹配,本题和LeetCode100.相同的树有共通之处

 1 class Solution {
 2 public:
 3     bool isSubtree(TreeNode* s, TreeNode* t) {
 4         if(!s && !t) return true;
 5         else if(!s ||!t) return false;
 6         else return isSametree(s,t) || isSubtree(s->left,t) || isSubtree(s->right,t);
 7     }
 8     bool isSametree(TreeNode *s,TreeNode* t){
 9         if(!s && !t) return true;
10         else if(!s || !t) return false;
11         else return s->val == t->val && isSametree(s->left,t->left) && isSametree(s->right,t->right);
12     }
13 };

参见大佬总结

https://leetcode-cn.com/problems/subtree-of-another-tree/solution/dui-cheng-mei-pan-duan-zi-shu-vs-pan-duan-xiang-de/

标签:LeetCode572,子树,TreeNode,一个,else,right,isSametree,&&,return
来源: https://www.cnblogs.com/fresh-coder/p/14258871.html