[LeetCode] Subtree of Another Tree
程序员文章站
2022-07-15 12:30:20
...
题目链接:点击打开链接
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 2Given tree t:
4 / \ 1 2Return 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 / 0Given 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);
}
};
推荐阅读
-
leetcode笔记:Invert Binary Tree
-
【leetcode】-700. Search in a Binary Search Tree 查找二叉搜索树
-
Leetcode——108. Convert Sorted Array to Binary Search Tree
-
Leetcode 108. Convert Sorted Array to Binary Search Tree
-
[LeetCode] Subtree of Another Tree
-
Leetcode 1519. Number of Nodes in the Sub-Tree With the Same Label (python)
-
LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label
-
LeetCode 236 -- 二叉树的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C语言版 )
-
LeetCode 235--二叉搜索树的最近公共祖先 ( Lowest Common Ancestor of a Binary Search Tree ) ( C语言版 )
-
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树