如果你想在校招中顺利拿到更好的offer,阿秀建议你多看看前人的经验 ,比如准备 、简历 、实习 、校招总结 、offer选择 、也欢迎来一起参加秋招打卡活动 等;如果你是计算机小白,学习/转行/校招路上感到迷茫或者需要帮助,可以点此联系阿秀;免费分享阿秀个人学习计算机以来的收集到的好资源,点此白嫖;如果你需要《阿秀的学习笔记》网站中求职相关知识点的PDF版本的话,可以点此下载
# 面试题26. 树的子结构 (opens new window)
输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
B是A的子结构, 即 A中有出现和B相同的结构和节点值。
例如: 给定的树 A:
3 / \ 4 5 / \ 1 2
给定的树 B:
4 / 1
返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。
示例 1:
输入:A = [1,2,3], B = [3,1]
输出:false
1
2
2
示例 2:
输入:A = [3,4,5,1,2], B = [4,1]
输出:true
1
2
2
限制:
0 <= 节点个数 <= 10000
1
# 1、改了许久的一种写法
执行用时 :72 ms, 在所有 C++ 提交中击败了61.82%的用户
内存消耗 :33.6 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
bool HasSubtreeCore(TreeNode* pRoot1, TreeNode* pRoot2) {
if (pRoot1 == nullptr && pRoot2 == nullptr) return true;
if (pRoot1 == nullptr && pRoot2 != nullptr) return false;
if (pRoot1 != nullptr && pRoot2 == nullptr) return true;
if (pRoot1->val == pRoot2->val)
return HasSubtreeCore(pRoot1->left, pRoot2->left) && HasSubtreeCore(pRoot1->right, pRoot2->right); // 这里必须是 与
else
return false;
}
bool isSubStructure(TreeNode* A, TreeNode* B)
{
if (A == nullptr || B == nullptr) return false;
return isSubStructure(A->left, B) || isSubStructure(A->right, B) || HasSubtreeCore(A,B);//注意这里的写法是 或
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
稍微优化一点点
执行用时 :64 ms, 在所有 C++ 提交中击败了81.74%的用户
内存消耗 :33.6 MB, 在所有 C++ 提交中击败了100.00%的用户
bool HasSubtreeCore(TreeNode* pRoot1, TreeNode* pRoot2) {
if (pRoot2 == nullptr) return true;// p2为空,不管p1是不是空都是正确的
if (pRoot1 == nullptr) return false;// p1为空,p2不为空,一定是错误的
if (pRoot1->val == pRoot2->val)
return HasSubtreeCore(pRoot1->left, pRoot2->left) && HasSubtreeCore(pRoot1->right, pRoot2->right);// 这里必须是 与
else
return false;
}
bool isSubStructure(TreeNode* A, TreeNode* B)
{
if (A == nullptr || B == nullptr) return false;
return isSubStructure(A->left, B) || isSubStructure(A->right, B) || HasSubtreeCore(A,B);//注意这里的写法是 或
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 2、以下这种写法是不对的,真的要小心
bool HasSubtreeCore(TreeNode* pRoot1, TreeNode* pRoot2) {
if ( pRoot2 == nullptr) return true;
if (pRoot1 == nullptr) return false;
if (pRoot1->val == pRoot2->val)
return HasSubtreeCore(pRoot1->left, pRoot2->left) && HasSubtreeCore(pRoot1->right, pRoot2->right);
else
return false;
}
bool isSubStructure(TreeNode* A, TreeNode* B)
{
if (A == nullptr || B == nullptr) return false;
//先判断p2是否在p1中
if (A->val == B->val) return HasSubtreeCore(A->left, B->left) && HasSubtreeCore(A->right, B->right); //不可以在这里直接判断其左右子树,因为有时候树中有可能有重复的数字
return isSubStructure(A->left, B) || isSubStructure(A->right, B);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[4,2,3,4,5,6,7,8,9] [4,8,9]
这种输入的话,会直接走到 if (A->val == B->val) 这一步,不会走到 isSubStructure(A->left, B) || isSubStructure(A->right, B) 这一步,因此不能这么写