概述
题目链接:点击打开链接
题目大意:略
解题思路:略
相关企业
- 字节跳动
- 亚马逊(Amazon)
AC 代码
- Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// 解决方案(1)
class Solution {
private boolean ok = false;
public boolean isSubStructure(TreeNode A, TreeNode B) {
if (null == B) {
return false;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(A);
TreeNode b = B;
while (!queue.isEmpty()) {
TreeNode a = queue.poll();
if (a.val == b.val) {
bfs(a, b);
if (ok) {
break;
} else {
b = B;
}
}
if (a.left != null) {
queue.offer(a.left);
}
if (a.right != null) {
queue.offer(a.right);
}
}
return ok;
}
private void bfs(TreeNode sa, TreeNode sb) {
Queue<TreeNode> qa = new LinkedList<>();
Queue<TreeNode> qb = new LinkedList<>();
qa.offer(sa);
qb.offer(sb);
while (!qb.isEmpty()) {
TreeNode a = qa.poll();
TreeNode b = qb.poll();
if (a == null || a.val != b.val) {
return;
}
if (a.left != null) {
qa.offer(a.left);
}
if (a.right != null) {
qa.offer(a.right);
}
if (b.left != null) {
qb.offer(b.left);
}
if (b.right != null) {
qb.offer(b.right);
}
}
ok = true;
}
}
// 解决方案(2)
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
return (A != null && B != null) && (recur(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B));
}
boolean recur(TreeNode A, TreeNode B) {
if(B == null) return true;
if(A == null || A.val != B.val) return false;
return recur(A.left, B.left) && recur(A.right, B.right);
}
}
- C++
class Solution {
public:
bool isSubStructure(TreeNode* A, TreeNode* B) {
return (A != nullptr && B != nullptr) && (recur(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B));
}
private:
bool recur(TreeNode* A, TreeNode* B) {
if(B == nullptr) return true;
if(A == nullptr || A->val != B->val) return false;
return recur(A->left, B->left) && recur(A->right, B->right);
}
};
最后
以上就是魔幻汽车为你收集整理的LeetCode(剑指 Offer)- 26. 树的子结构的全部内容,希望文章能够帮你解决LeetCode(剑指 Offer)- 26. 树的子结构所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复