LeetCode(剑指 Offer)- 26. 树的子结构
Posted 放羊的牧码
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(剑指 Offer)- 26. 树的子结构相关的知识,希望对你有一定的参考价值。
题目链接:点击打开链接
题目大意:略
解题思路:略
相关企业
- 字节跳动
- 亚马逊(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刷题Python剑指 Offer 26. 树的子结构
[LeetCode]剑指 Offer 33. 二叉搜索树的后序遍历序列
[LeetCode]剑指 Offer 33. 二叉搜索树的后序遍历序列